﻿
/********************************************************
 // Module Name    : Run Time Show Window
 // Purpose        : *	Main Application Panel.
                     *  Structure:
                     *      (ToolBar) -> to be added to owning window
                     *	  	 tabPanel(TabControl)
                     *		 (StatusBar)
                     *  
 // Class Used     : GlobalVariable.cs, CommonFunctions.cs
 // Created By     : Harwinder 
 // Date           : --
**********************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Utility;
using VAdvantage.Logging;
using VAdvantage.Grids;
using System.Threading;
using VAdvantage.Classes;
using VAdvantage.Panels;
using VAdvantage.Framework;
using System.Text;
using VAdvantage.Controls;
using VAdvantage.Model;
using System.Reflection;
using VAdvantage.Process;
using VAdvantage.ProcessEngine;
using System.ComponentModel;
using VAdvantage.Print;
using SL4PopupMenu;
using System.Data;
using System.Collections;
using System.IO;
using VAdvantage.DataBase;
//using VAdvantage.WorkSpace;
using System.Windows.Controls.Primitives;
using VAdvantage.Dialogs;
using VAdvantage.ProcessEngine;
using Vadvantage.Model;
using VAdvantage.DataServiceBasic;
using System.Collections.ObjectModel;

namespace VAdvantage.Apps
{
    public partial class APanel : UserControl, IDisposable, ASyncProcess, ASyncRefreshUI, IBusy
    {

        #region Declaration
        /* Context */
        private Ctx _ctx;
        /* Logger */
        private VLogger log;
        /** Workbench Model                                 */
        private GridWorkbench _mWorkbench;
        /* wondow Number */
        int _curWindowNo;
        /* query */
        Query query;
        /* current Grid Tab */
        private GridTab _curTab;
        /* Current Grid Controller */
        private GridController _curGC;
        /* current Tab panel */
        private Controls.VTabControl _curWinTab = null;
        /* Tab Index */
        int _curTabIndex;
        /* Sort Tab */
        private VSortTab _curAPanelTab;
        /* Current Page */
        private int _curPage = 0;
        /* Total Page */
        private int _totalPage = 0;
        /* Disposing */
        private bool disposing;
        /* pause Action */
        private bool blockEvent;
        /* Is Data Change */
        private bool isCurentRowDirty;
        /* Action */
        private Action saveAction = null;
        PopupMenu printFormat = null;


        // Add for Dynamin action
        /* Treeview for dynamic + static Action items (Left)*/
        AccordionItem actionItem = null;
        AccordionItem historyItem = null;
        private TreeView lstAction = null;
        /*  Treeview for dynamic + static Action items (Right) */
        private TreeView lstRelated = null;
        private int actionItemCount_Left;
        private readonly int actionItemCount_Right;

        //End


        #endregion

        #region "ToolBarButtons"
        private AppsAction aPrevious, aNext, aParent, aDetail, aFirst, aLast, aPageDown, aPageUp, aPageFirst, aPageLast,
                               aNew, aCopy, aDelete, aDeleteSelection, aIgnore, aPrint, aSave, aRefresh, aMulti, aNewG, aFind,
                               aAttachment, aChat, aEmail, aLetter, aSms, aFaxEMail, aAppointment, aEmailAttach,
                               aWorkflow, aZoomAcross, aRequest, aUserDef, aArchive, aImportMap, aMarkToExport,
                               aPreference, aHelp, aTask, aSubscribe;

        /** Save Button			*/
        // public AppsAction 
        /** Private Lock Button	*/
        public AppsAction aLock, aRoleCenterView;
        //	Local (added to toolbar)
        private AppsAction aReport, aEnd, aExit;
        private bool newRow;
        // Show Personal Lock		
        private bool _isPersonalLock;
        //Last Modifier of Action Event					
        private int _lastModifiers;

        #endregion

        public APanel()
        {
            InitializeComponent();
            _ctx = Envs.GetCtx();
            //
            try
            {
                log = Logging.VLogger.GetVLogger(typeof(APanel).FullName);
                //InitializeComponent();
                //CommonFunctions.SetTabProperties(tabPanel);
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, "", e);
            }

            _isPersonalLock = MRole.GetDefault().IsPersonalLock();

            CreateToolBarMenu();

            actionItemCount_Right = lstRelated.Items.Count;

        }

        #region Function

        /*Change Request*/

        /// <summary>
        /// Show Action against window Setting
        /// </summary>
        /// <param name="mwindow"></param>
        public void CreateActionToolbar(GridWindow mwindow)
        {

            if (mwindow.IsAppointment())
            {
                lstAction.Items.Add(aAppointment.GetTreeViewItem());
            }
            if (mwindow.IsTask())
            {
                lstAction.Items.Add(aTask.GetTreeViewItem());
            }
            if (mwindow.IsEmail())
            {
                lstAction.Items.Add(aEmail.GetTreeViewItem());
            }

            if (mwindow.IsLetter())
            {
                lstAction.Items.Add(aLetter.GetTreeViewItem());
            }
            if (mwindow.IsSms())
            {
                lstAction.Items.Add(aSms.GetTreeViewItem());
            }

            if (mwindow.IsFaxEmail())
            {
                lstAction.Items.Add(aFaxEMail.GetTreeViewItem());
            }

            actionItemCount_Left = lstAction.Items.Count;
            if (actionItemCount_Left > 0)
            {
                actionItem.IsSelected = true;
            }
        }

        /// <summary>
        /// Create Tool bar items And Tree View items
        /// </summary>
        private void CreateToolBarMenu()
        {


            aNew = AddAction("New", "New", "New", false, false);
            //aCopy = AddAction("Copy", "Copy", "Copy", false, false);
            aDelete = AddAction("Delete", "Delete", "Delete", false, false);

            aSave = AddAction("Save", "Save", "Save", false, false);
            aIgnore = AddAction("Ignore", "Ignore", "Ignore", false, false);
            aRefresh = AddAction("Refresh", "Refresh", "Refresh", false, false);
            aFind = AddAction("Find", "Find", "Find", true, false);	//	



            aReport = AddAction("Report", "Report", "Report", false, false);
            aPrint = AddAction("Print", "Print", "Print", false, false);
            aHelp = AddAction("Help", "Help", "Help", false, false);

            aImportMap = AddAction("Import", "Import", "Import", false, false);
            CreateLeftTree();
            CreteRightTree();
            CreateUpperToolbar();


            CreatePageNavigator();



            //if (_isPersonalLock)
            //    aLock = AddAction("Lock", "Lock", "Lock", true, false);		//	toggle

            toolBar.ToolBarItems.Add(aIgnore.GetButton());		//	ESC
            toolBar.ToolBarItems.Add(aNew.GetButton());
            // toolBar.ToolBarItems.Add(aCopy.GetButton());
            toolBar.ToolBarItems.Add(aDelete.GetButton());
            // toolBar.ToolBarItems.Add(aDeleteSelection.GetButton());
            toolBar.ToolBarItems.Add(aSave.GetButton());
            toolBar.ToolBarItems.Add(aRefresh.GetButton());      //  F5
            toolBar.ToolBarItems.Add(aFind.GetButton());
            //toolBar.ToolBarItems.Add(aAttachment.GetButton());
            //toolBar.ToolBarItems.Add(aChat.GetButton());
            //toolBar.ToolBarItems.Add(aMulti.GetButton());
            //if (_isPersonalLock)
            //{
            //    toolBar.ToolBarItems.Add(aLock.GetButton());
            //}
            //toolBar.ToolBarItems.Add(aPageFirst.GetButton());
            //toolBar.ToolBarItems.Add(aPageUp.GetButton());

            // toolBar.ToolBarItems.Add(aFirst.GetButton());
            // toolBar.ToolBarItems.Add(aPrevious.GetButton());
            //  toolBar.ToolBarItems.Add(aNext.GetButton());
            // toolBar.ToolBarItems.Add(aLast.GetButton());
            // toolBar.ToolBarItems.Add(aPageDown.GetButton());
            //toolBar.ToolBarItems.Add(aPageLast.GetButton());

            toolBar.ToolBarItems.Add(aReport.GetButton());

            //printFormat = new PopupMenu();
            //printFormat.AddTrigger(TriggerTypes.LeftClick, aReport.GetButton());
            //PopupMenuItem reportmnu = new PopupMenuItem(null, Msg.GetMsg("Report"), null);
            //reportmnu.Click += (ov, ev) =>
            //{
            //    Cmd_Report();
            //};
            //printFormat.AddItem(reportmnu);

            toolBar.ToolBarItems.Add(aPrint.GetButton());
            toolBar.ToolBarItems.Add(aHelp.GetButton());
            // toolBar.ToolBarItems.Add(aSubscribe.GetButton());
            //  toolBar.ToolBarItems.Add(aImportMap.GetButton());

            CreateInfoBar();


            aPageDown.SetEnabled(false);
            aPageUp.SetEnabled(false);
            aPageFirst.SetEnabled(false);
            aPageLast.SetEnabled(false);

        }

        private void CreatePageNavigator()
        {
            aPageUp = AddAction("PageUp", "PageUp", "PageUp", false, false);
            aPageFirst = AddAction("PageFirst", "PageFirst", "FirstPage", false, false);
            aPageDown = AddAction("PageDown", "PageDown", "PageDown", false, false);
            aPageLast = AddAction("PageLast", "PageLast", "LastPage", false, false);

            Grid grd = new Grid();
            grd.MinWidth = 24;

            ImageBrush imgb = new ImageBrush() { ImageSource = Envs.LoadImageSource("Toolbar/Number22.png") };
            grd.Background = imgb;
            //TextBlock txt = new TextBlock();
            //txt.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            //txt.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            // txt.Margin = new Thickness(3);
            grd.Children.Add(statusBar.Pages);
            //statusBar.PagingText = txt;

            statusBar.PageNavigator.Children.Add(aPageFirst.GetButton(""));
            statusBar.PageNavigator.Children.Add(aPageUp.GetButton(""));
            statusBar.pageNavigator.Children.Add(grd);
            statusBar.PageNavigator.Children.Add(aPageDown.GetButton(""));
            statusBar.PageNavigator.Children.Add(aPageLast.GetButton(""));
            statusBar.SelectionChanged += new SelectionChangedEventHandler(statusBar_SelectionChanged);
        }

        void statusBar_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ComboBox)
            {
                int index = ((ComboBox)sender).SelectedIndex;
                _curPage = index;
                NavigatePage(false, false);
            }
        }

        private void CreateUpperToolbar()
        {
            aFirst = AddAction("First", "First", "First", false, false);
            aPrevious = AddAction("Previous", "Previous", "Previous", false, false);
            aNext = AddAction("Next", "Next", "Next", false, false);
            aLast = AddAction("Last", "Last", "Last", false, false);
            aMulti = AddAction("Multi", "Multi", "Multi", true, false);
            aNewG = AddAction("NewG", "NewG", "NewG", false, false);
            aDeleteSelection = AddAction("MultiDelete", "MultiDelete", "MultiDelete", false, false);

            spNavigation.Children.Add(aFirst.GetButton(""));
            spNavigation.Children.Add(aPrevious.GetButton(""));
            spNavigation.Children.Add(aNext.GetButton(""));
            spNavigation.Children.Add(aLast.GetButton(""));
            spToggle.Children.Add(aNewG.GetButton(""));
            spToggle.Children.Add(aDeleteSelection.GetButton(""));
            spToggle.Children.Add(aMulti.GetButton(""));


        }

        /// <summary>
        /// Create tree Items (right expander)
        /// </summary>
        private void CreteRightTree()
        {
            // relatedItem.Header = Msg.GetMsg(_ctx, "Related");
            // StackPanel rightAccordion = new StackPanel() { Orientation = Orientation.Vertical };
            Accordion rightAccordion = new Accordion() { HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, BorderThickness = new Thickness(0) };
            rightAccordion.ItemContainerStyle = this.Resources["AccordionItemStyle1"] as Style;

            rightPanel.Child = rightAccordion;

            AccordionItem relatedItem = GetAccordingItem("Related");
            relatedItem.IsSelected = true;
            // StackPanel lstRelated = new StackPanel() { Orientation = System.Windows.Controls.Orientation.Vertical };
            lstRelated = GetTreeView();
            relatedItem.Content = lstRelated;
            rightAccordion.Items.Add(relatedItem);
            //rightAccordion.Children.Add(relatedItem);

            //TreeView tvRight = new TreeView();
            //tvRight.Background = new SolidColorBrush(Colors.Transparent);
            //tvRight.BorderThickness = new Thickness(0);
            //rightPanel.Child = tvRight;
            TreeViewItem itm = null;
            if (MRole.GetDefault().IsShowPreference())
            {
                //. aUserDef = AddAction("WinSize", mTools, Keys.None, false);
                // mTools.DropDown.Items.Add(new ToolStripSeparator());
                aPreference = AddAction("Preference", "Preference", "Preference", false, true);
                itm = aPreference.GetTreeViewItem();
                //itm.Margin = new Thickness(-10, 0, 0, 0);
                // lstRelated.Children.Add(itm);
                lstRelated.Items.Add(itm);
                //tvRight.Items.Add(itm);
            }

            if (AEnv.IsWorkflowProcess())
                aWorkflow = AddAction("Workflow", "Workflow", "Workflow", false, true);


            aZoomAcross = AddAction("ZoomAcross", "ZoomAcross", "ZoomAcross", false, true);
            aRequest = AddAction("Request", "Request", "Request", false, true);
            aSubscribe = AddAction("Subscribe", "Subscribe", "Subscribe", true, true);
            aCopy = AddAction("Copy", "Copy", "Copy", false, true);
            aMarkToExport = AddAction("Mark", "Mark", "Mark", true, true);
            itm = aSubscribe.GetTreeViewItem();
            lstRelated.Items.Add(itm);

            itm = aZoomAcross.GetTreeViewItem();
            //itm.Margin = new Thickness(-10, 0, 0, 0);

            lstRelated.Items.Add(itm);
            //lstRelated.Children.Add(itm);
            itm = aRequest.GetTreeViewItem();
            // itm.Margin = new Thickness(-10, 0, 0, 0);
            lstRelated.Items.Add(itm);

            itm = aCopy.GetTreeViewItem();
            lstRelated.Items.Add(itm);

            itm = aMarkToExport.GetTreeViewItem();
            lstRelated.Items.Add(itm);
            //itm = aArchive.GetListBoxItem();
            //// itm.Margin = new Thickness(-10, 0, 0, 0);
            //lstRelated.Items.Add(itm);
            if (aWorkflow != null)
            {
                lstRelated.Items.Add(aWorkflow.GetTreeViewItem());
            }

            //add lock in side tree
            if (_isPersonalLock)
            {
                aLock = AddAction("Personal Lock", "Lock", "Personal Lock", true, true);
                itm = aLock.GetTreeViewItem();
                lstRelated.Items.Add(itm);
            }
        }


        private AccordionItem GetAccordingItem(String header)
        {
            AccordionItem itm = new AccordionItem();
            //itm.Style = this.Resources["AItem"] as Style;
            // itm.HeaderTemplate = this.Resources["headerTemplate"] as DataTemplate;
            itm.Header = Msg.GetMsg(_ctx, header);
            return itm;
        }

        private TreeView GetTreeView()
        {
            TreeView itm = new TreeView();
            itm.Style = this.Resources["Atreeview"] as Style;
            // itm.HeaderTemplate = this.Resources["headerTemplate"] as DataTemplate;
            return itm;
        }

        /// <summary>
        ///  Create tree Items (left expander)
        /// </summary>
        private void CreateLeftTree()
        {
            
            Accordion leftAccordion = new Accordion() { HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, BorderThickness = new Thickness(0) };
            leftAccordion.ItemContainerStyle = this.Resources["AccordionItemStyle1"] as Style;
            //StackPanel leftAccordion = new StackPanel() { Orientation = Orientation.Vertical };

            leftPanel.Child = leftAccordion;

            actionItem = GetAccordingItem("Action");
            //actionItem.IsExpanded = true;
            // StackPanel lstAction = new StackPanel() { Orientation = System.Windows.Controls.Orientation.Vertical };
            lstAction = GetTreeView();
            actionItem.Content = lstAction;
            leftAccordion.Items.Add(actionItem);
            // leftAccordion.Children.Add(actionItem);


            historyItem = GetAccordingItem("HistorySearch");
            //StackPanel lstHistory = new StackPanel() { Orientation = System.Windows.Controls.Orientation.Vertical };
            TreeView lstHistory = GetTreeView();
            // historyItem.IsExpanded = true;
            historyItem.Content = lstHistory;
            leftAccordion.Items.Add(historyItem);
            // leftAccordion.Children.Add(historyItem);

            AccordionItem otherItem = GetAccordingItem("Other");
            //StackPanel lstOther = new StackPanel() { Orientation = System.Windows.Controls.Orientation.Vertical };
            TreeView lstOther = GetTreeView();
            otherItem.Content = lstOther;
            leftAccordion.Items.Add(otherItem);
            //leftAccordion.Children.Add(otherItem);


            // TreeView tvLeft = new TreeView();
            //tvLeft.Background = new SolidColorBrush(Colors.Transparent);
            //tvLeft.BorderThickness = new Thickness(0);
            //leftPanel.Child = tvLeft;

            //ATreeViewItem header1 = new ATreeViewItem();
            // header1.Margin = new Thickness(-10, -5, 0, 0);
            // header1.Header = Msg.GetMsg(_ctx, "Related");
            // header1.FontWeight = FontWeights.SemiBold;
            //// header1.Foreground = new SolidColorBrush(Colors.Black);
            // header1.IsExpanded = true;
            // header1.FontSize = 12;
            // tvLeft.Items.Add(header1);

            //ATreeViewItem header2 = new ATreeViewItem();
            //header2.Margin = new Thickness(-10, 10, 0, 0);
            //header2.Header = Msg.GetMsg(_ctx, "Other");
            //header2.FontWeight = FontWeights.SemiBold;
            //header2.Foreground = new SolidColorBrush(Colors.Black);
            //header2.IsExpanded = true;
            //header2.FontSize = 12;
            //tvLeft.Items.Add(header2);


            //header2.Items.Add(new ATreeViewItem() { Header = "Exemple1" });
            //header2.Items.Add(new ATreeViewItem() { Header = "Exemple2" });



            //Left Side
            // AddAction("Home", "Home", "Home", false);
            aAttachment = AddAction("Attachment", "Attachment", "Attachment", true, true);		//	toggle
            aChat = AddAction("Chat", "Chat", "Chat", true, true);		//	toggle


            aImportMap = AddAction("Import", "Import", "Import", false, true);

            aMarkToExport = AddAction("ExportToClient", "ExportToClient", "ExportToClient", false, true);

            aArchive = AddAction("Archive", "Archive", "Archive", false, true);



            aEmailAttach = AddAction("EmailAttach", "EmailAttach", "EmailAttach", false, true);

            aRoleCenterView = AddAction("RoleCenterView", "RoleCenterView", "RoleCenterView", false, true);

            // header1.Items.Add(aAppointment.GetTreeViewItem());


            lstHistory.Items.Add(aChat.GetTreeViewItem());
            //header1.Items.Add(aEmailAttach.GetTreeViewItem());
            lstHistory.Items.Add(aAttachment.GetTreeViewItem());

            lstHistory.Items.Add(aArchive.GetTreeViewItem());

            //header2.Items.Add(aImportMap.GetTreeViewItem());
            lstOther.Items.Add(aRoleCenterView.GetTreeViewItem());

            lstOther.Items.Add(aEmailAttach.GetTreeViewItem());

            lstOther.Items.Add(aImportMap.GetTreeViewItem());

            /*DynamicAction*/

            aAppointment = AddAction("Appointment", "Appointment", "Appointment", false, true);
            aEmail = AddAction("EMail", "EMailSupport", "EMail", false, true);
            //    aEmail = AddAction("EMail", "EMailSupport", "EMail", false);
            aLetter = AddAction("Letter", "Letter", "Letter", false, true);
            aSms = AddAction("Sms", "Sms", "Sms", false, true);
            aTask = AddAction("Task", "Task", "Task", false, true);
            aFaxEMail = AddAction("FaxEMail", "FaxEMail", "Fax", false, true);


            // header2.Items.Add(aRoleCenterView.GetTreeViewItem());
            //header2.Items.Add(new ATreeViewItem() { Header = "Role Center KPI" });
            //header2.Items.Add(aEmailAttach.GetTreeViewItem());

        }

        /// <summary>
        /// Cretae Info Window's items
        /// </summary>
        private void CreateInfoBar()
        {
            //SL4PopupMenu.PopupMenu
            //Info Window

            ToolBarButton info = new ToolBarButton();
            info.Icon = Envs.LoadImageSource("Toolbar/Info22.png");
            info.Text = "Infos";
            PopupMenu infoWin = new PopupMenu();

            // PopupMenuItem mnu = new PopupMenuItem("Images/Toolbar/InfoProduct16.png", Msg.GetMsg(_ctx, "InfoProduct"), null);
            PopupMenuItem mnu = new PopupMenuItem(null, Msg.GetMsg(_ctx, "InfoProduct"), null);
            mnu.ImageSource = Envs.LoadImageSource("Toolbar/InfoProduct16.png");
            mnu.Name = "InfoProduct";
            mnu.Click += mnu_Click;
            infoWin.AddItem(mnu);

            //    mnu = new PopupMenuItem(EnvConstants.ApplicationName + ";component/Images/Toolbar/InfoBPartner16.png", Msg.GetMsg(_ctx, "InfoBPartner"), null);
            mnu = new PopupMenuItem(null, Msg.GetMsg(_ctx, "InfoBPartner"), null);
            mnu.ImageSource = Envs.LoadImageSource("Toolbar/InfoBPartner16.png");
            mnu.Name = "InfoBPartner";
            mnu.Click += mnu_Click;
            infoWin.Items.Add(mnu);

            if (MRole.GetDefault().IsShowAcct())
            {
                // mnu = new PopupMenuItem("Images/Toolbar/InfoAccount16.png", Msg.GetMsg(_ctx, "InfoAccount"), null);]
                mnu = new PopupMenuItem(null, Msg.GetMsg(_ctx, "InfoAccount"), null);
                mnu.ImageSource = Envs.LoadImageSource("Toolbar/InfoAccount16.png");
                mnu.Name = "InfoAccount";
                mnu.Click += mnu_Click;
                infoWin.AddItem(mnu);
            }

            infoWin.AddSeparator();

            // mnu = new PopupMenuItem("../Images/Toolbar/Info16.png", Msg.GetMsg(_ctx, "InfoOrder"), null);
            mnu = new PopupMenuItem(null, Msg.GetMsg(_ctx, "InfoOrder"), null);
            mnu.ImageSource = Envs.LoadImageSource("Toolbar/Info16.png");
            mnu.Name = "InfoOrder";
            mnu.Click += mnu_Click;
            infoWin.AddItem(mnu);

            // mnu = new PopupMenuItem("Images/Toolbar/Info16.png", Msg.GetMsg(_ctx, "InfoInvoice"), null);
            mnu = new PopupMenuItem(null, Msg.GetMsg(_ctx, "InfoInvoice"), null);
            mnu.ImageSource = Envs.LoadImageSource("Toolbar/Info16.png");
            mnu.Name = "InfoInvoice";
            mnu.Click += mnu_Click;
            infoWin.AddItem(mnu);

            // mnu = new PopupMenuItem("Images/Toolbar/Info16.png", Msg.GetMsg(_ctx, "InfoInOut"), null);
            mnu = new PopupMenuItem(null, Msg.GetMsg(_ctx, "InfoInOut"), null);
            mnu.ImageSource = Envs.LoadImageSource("Toolbar/Info16.png");
            mnu.Name = "InfoInOut";
            mnu.Click += mnu_Click;
            infoWin.AddItem(mnu);

            // mnu = new PopupMenuItem("Images/Toolbar/Info16.png", Msg.GetMsg(_ctx, "InfoPayment"), null);
            mnu = new PopupMenuItem(null, Msg.GetMsg(_ctx, "InfoPayment"), null);
            mnu.ImageSource = Envs.LoadImageSource("Toolbar/Info16.png");
            mnu.Name = "InfoPayment";
            mnu.Click += mnu_Click;
            infoWin.AddItem(mnu);

            //mnu = new PopupMenuItem("Images/Toolbar/Info16.png", Msg.GetMsg(_ctx, "InfoCashLine"), null);
            mnu = new PopupMenuItem(null, Msg.GetMsg(_ctx, "InfoCashLine"), null);
            mnu.ImageSource = Envs.LoadImageSource("Toolbar/Info16.png");
            mnu.Name = "InfoCashLine";
            mnu.Click += mnu_Click;
            infoWin.AddItem(mnu);

            // mnu = new PopupMenuItem("Images/Toolbar/Info16.png", Msg.GetMsg(_ctx, "InfoAssignment"), null);
            //mnu = new PopupMenuItem(null, Msg.GetMsg(_ctx, "InfoAssignment"), null);
            //mnu.ImageSource = Envs.LoadImageSource("Toolbar/Info16.png");
            //mnu.Name = "InfoAssignment";
            //mnu.Click += mnu_Click;
            //infoWin.AddItem(mnu);

            //  mnu = new PopupMenuItem("Images/Toolbar/Info16.png", Msg.GetMsg(_ctx, "InfoAsset"), null);
            mnu = new PopupMenuItem(null, Msg.GetMsg(_ctx, "InfoAsset"), null);
            mnu.ImageSource = Envs.LoadImageSource("Toolbar/Info16.png");
            mnu.Name = "InfoAsset";
            mnu.Click += mnu_Click;
            infoWin.AddItem(mnu);

            infoWin.AddTrigger(TriggerTypes.LeftClick, info);

            toolBar.ToolBarItems.Add(info);
        }

        /// <summary>
        /// Info window link handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void mnu_Click(object sender, RoutedEventArgs e)
        {

            PopupMenuItem s = (PopupMenuItem)sender;

            AEnv.ActionPerformed(s.Name, _curWindowNo, (FrameworkElement)this);

            //   throw new NotImplementedException();
        }

        /// <summary>
        /// GetTile
        /// </summary>
        /// <returns></returns>
        public String GetTitle()
        {
            if (_mWorkbench.GetWindowCount() > 1)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(_mWorkbench.GetName()).Append("  ")
                    .Append(_ctx.GetContext("#AD_User_Name")).Append("@")
                    .Append(_ctx.GetContext("#AD_Client_Name")).Append(".")
                    .Append(_ctx.GetContext("#AD_Org_Name")).Append(" [")
                    .Append(_ctx.GetContext("#DB_UID")).Append("]");
                return sb.ToString();
            }
            return Envs.GetHeader(_ctx, _curWindowNo);
        }

        /// <summary>
        ///	Add (Toggle) Action to Toolbar and Menu
        /// </summary>
        /// <param name="actionName"></param>
        /// <param name="menu"></param>
        /// <param name="accelerator"></param>
        /// <param name="toggle"></param>
        /// <returns></returns>
        private AppsAction AddAction(String actionName, String imageName, String toolTipText, bool toggle, bool isSmall)
        {
            AppsAction action = new AppsAction(actionName, imageName, toolTipText, toggle, isSmall);
            if (action != null)
            {
                //if (!actionName.Equals("Report", StringComparison.OrdinalIgnoreCase))
                action.ActionPerformed += new RoutedEventHandler(ActionPerformed);
            }
            //if (menu != null)
            //    menu.DropDownItems.Add(action.GetMenuItem());
            //  action.SetDelegate(this);
            //	AbstractButton b = action.getButton();
            //	String s = null;
            //	if (b != null)
            //		s = b.getToolTipText();
            //
            return action;
        }

        //saves the list
        private List<KeyNamePair> _list = new List<KeyNamePair>();
        KeyNamePair pp = null;
        void CreatePrintFormat(int AD_Table_ID)
        {
            pp = null;
            int AD_Client_ID = Envs.GetContext().GetAD_Client_ID();
            //
            String sql = MRole.GetDefault().AddAccessSQL(
                "SELECT AD_PrintFormat_ID, Name, AD_Client_ID "
                    + "FROM AD_PrintFormat "
                    + "WHERE AD_Table_ID='" + AD_Table_ID + "' AND IsTableBased='Y' "
                    + "ORDER BY AD_Client_ID DESC, IsDefault DESC, Name",		//	Own First
                "AD_PrintFormat", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);

            IDataReader dr = DB.ExecuteReader(sql);
            try
            {
                while (dr.Read())
                {
                    pp = new KeyNamePair(Util.GetValueOfInt(dr[0].ToString()), dr[1].ToString());
                    if (Utility.Util.GetValueOfInt(dr[2].ToString()) == AD_Client_ID)
                    {
                        _list.Add(pp);
                    }
                }
                dr.Close();

            }
            catch
            {
            }
        }

        ///	Dynamic Panel Initialization - either single window or workbench.
        ///  <pre>
        ///   either
        ///   - Workbench tabPanel    (VTabbedPane)
        ///       - Tab               (GridController)
        ///   or
        ///   - Workbench tabPanel    (VTabbedPane)
        ///       - Window            (VTabbedPane)
        ///           - Tab           (GridController)
        ///   </pre>
        ///
        /// </summary>
        /// <param name="AD_Workbench_ID"></param>
        /// <param name="AD_Window_ID"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        internal bool InitPanel(int AD_Workbench_ID, int AD_Window_ID, Query query, AWindow host)
        {
            //log.Info("WB=" + AD_Workbench_ID + ", Win=" + AD_Window_ID + ", Query=" + query);
            //this.Name = "APanel" + AD_Window_ID.ToString();
            //;
            //query = _query;

            windowHost = host;
            //  Single Window
            if (AD_Workbench_ID == 0)
                _mWorkbench = new GridWorkbench(_ctx, AD_Window_ID);
            else
            //  Workbench
            {
                //	m_mWorkbench = new MWorkbench(m_ctx);
                //	if (!m_mWorkbench.initWorkbench (AD_Workbench_ID))
                //	{
                //		log.log(Level.SEVERE, "APanel.initWindow - No Workbench Model");
                //		return false;
                //	}
                //	tabPanel.setWorkbench(true);
                //	tabPanel.addChangeListener(this);
                //ShowMessage.Warn("Not implemented yet", true, "", "IniTPanel");// ADialog.warn(0, this, "", "Not implemented yet");
                return false;
            }

            // System.Drawing.Size? windowSize = _mWorkbench.GetWindowSize();

            /**
             *  WorkBench Loop
             */
            for (int wb = 0; wb < _mWorkbench.GetWindowCount(); wb++)
            {
                //  Get/set WindowNo
                _curWindowNo = Envs.CreateWindowNo(this);			                //  Timing: ca. 1.5 sec
                _mWorkbench.SetWindowNo(wb, _curWindowNo);
                //  Set AutoCommit for this Window
                _ctx.SetAutoCommit(_curWindowNo, _ctx.IsAutoCommit());
                bool autoNew = _ctx.IsAutoNew();
                _ctx.SetAutoNew(_curWindowNo, autoNew);

                //_ctx.SetHideClientOrg(_curWindowNo,_ctx.GetHideClientOrg());   
                //  Workbench Window


                Controls.VTabbedPane window = null;
                //  just one window
                if (_mWorkbench.GetWindowCount() == 1)
                {
                    window = tabPanel;
                    // window.SetWorkbench(false);
                }
                else
                {
                    // VTabbedPane tp = new VTabbedPane(false);
                    // window = tp;
                }


                window.SelectionChanged += StateChanged;

                int wbType = _mWorkbench.GetWindowType(wb);

                /**
                 *  Window
                 */
                if (wbType == GridWorkbench.TYPE_WINDOW)
                {
                    // DateTime timeSpan = DateTime.Now;
                    // log.Severe("Start Step1 <===>" + timeSpan.TimeOfDay.ToString());
                    //GridWindowVO wVO = AEnv.GetMWindowVO(_curWindowNo, _mWorkbench.GetWindowID(wb), 0);
                    GridWindowVO wVO = AEnv.GetMWindowVO(_curWindowNo, _mWorkbench.GetWindowID(wb), 0);
                    if (wVO == null)
                    {
                        ShowMessage.Error("AccessTableNoView", null, "(No Window Model Info)");
                        //ADialog.error(0, null, "AccessTableNoView", "(No Window Model Info)");
                        return false;
                    }
                    // log.Severe("End Step 1  start Step2 <===>" + (timeSpan - DateTime.Now).ToString());
                    GridWindow mWindow = new GridWindow(wVO);
                    //	Set SO/AutoNew for Window
                    _ctx.SetIsSOTrx(_curWindowNo, mWindow.IsSOTrx());
                    if (!autoNew && mWindow.IsTransaction())
                        _ctx.SetAutoNew(_curWindowNo, true);
                    _mWorkbench.SetMWindow(wb, mWindow);
                    //}   //  Type-MWindow


                    //Dyanamic Action (new Change)



                    _ctx.SetContext(_curWindowNo, "WindowName", _mWorkbench.GetName(wb));




                    //System.Drawing.Size? windowSize = _mWorkbench.GetWindowSize();


                    //  int wbType = _mWorkbench.GetWindowType(wb);
                    // _curWindowNo = _mWorkbench.GetWindowNo(wb);
                    /**
                     *  Window
                     */
                    //if (wbType == GridWorkbench.TYPE_WINDOW)
                    //{

                    // Dictionary<int, GridController> includedMap = new Dictionary<int, GridController>(4);

                    // GridWindow mWindow = _mWorkbench.GetMWindow(wb);

                    //log.Severe("End Step 2  start Step3 <===>" + (timeSpan - DateTime.Now).ToString());
                    int tabSize = mWindow.GetTabCount();
                    bool goSingleRow = query != null;	//	Zoom Query
                    for (int tab = 0; tab < tabSize; tab++)
                    {
                        GridTab gTab = _mWorkbench.GetMWindow(wb).GetTab(tab);
                        CreateAndAddTab(window, wb, tab, goSingleRow, mWindow, gTab, query);
                    }   //  Tab Loop
                }

                //  Single Workbench Window Tab
                if (_mWorkbench.GetWindowCount() == 1)
                {
                    //ToolTip tTip = new ToolTip();
                    // tTip.SetToolTip(window, _mWorkbench.GetDescription());
                    //.setToolTipText(m_mWorkbench.getDescription(wb));
                }
                else
                //  Add Workbench Window Tab
                {
                    //tabPanel.addTab(m_mWorkbench.getName(wb), m_mWorkbench.getIcon(wb), window, m_mWorkbench.getDescription(wb));
                }
                //  Used for VAdvantage.Utility.Env.getHeader

            }

            //  stateChanged (<->) triggered
            //toolBar.setName(getTitle());
            //_curTab.GetTableObj().setChanged(false);
            ////	Set Detail Button
            // aDetail.SetEnabled(0 != _curWinTab.TabCount-1);


            ///	Size
            //if (windowSize != null)
            //{
            //    // this.PreferredSize = windowSize.Value;//  setPreferredSize(windowSize);
            //    //this.PreferredSize = new Size(windowSize.Value.Width, windowSize.Value.Height);
            //    this.ParentForm.Size = new Size(windowSize.Value.Width, windowSize.Value.Height);
            //    //this.Size = new Size(windowSize.Value.Width,windowSize.Value.Height);
            //}
            //Dimension size = getPreferredSize();
            //log.Info( "fini - " + size);
            //m_curWinTab.requestFocusInWindow();
            //blockEvent = true;

            //  tabPanel.TabBackGroundColor = Color.Transparent;
            /**************Developed by Raghu***********************/
            //Date:19/04/2010
            //Check to enable Email Icon on tool for multi-row display setting
            //if (!_curTab.IsSingleRow())
            //{
            //    aEmail.SetEnabled(true);
            //    aLetter.SetEnabled(aAttachment.IsEnabled() && _curTab.IsAllowLetter);
            //    //aLetter.SetEnabled(true);
            //    aSms.SetEnabled(true);
            //}
            //if (Envs.GetCtx().GetShowMiniGrid())//Enable email icon on tool bar on minigid option
            //{
            //    aEmail.SetEnabled(true);
            //    aLetter.SetEnabled(aAttachment.IsEnabled() && _curTab.IsAllowLetter);
            //    //aLetter.SetEnabled(true);
            //    aSms.SetEnabled(true);
            //}
            /*********************************************************/
            return true;
        }

        AWindow windowHost = null;

        private void CreateAndAddTab(VTabbedPane window, int wb, int tab, bool goSingleRow, GridWindow mWindow, GridTab gTab, Query query)
        {

            Dispatcher.BeginInvoke(delegate
            {
                bool included = false;
                //  MTab

                //Thread.Sleep(1000);

                //  Query first tab
                if (tab == 0)
                {
                    //SetWindowName(mWindow.GetName());
                    SetWindowName(mWindow.GetDisplayName());

                    //New Change(un-nessessry 
                    CreateActionToolbar(mWindow);

                    //  initial user query for single workbench tab
                    if (_mWorkbench.GetWindowCount() == 1)
                    {
                        //query = InitialQuery(query, gTab,	//	onlyCurrentRows 
                        //    wb == 0 && _GridWindow.IsTransaction());
                        //if (!_showTargetWindow)
                        //{
                        //    this.Dispose(true);
                        //    return false;
                        //}


                        //if (query != null && query.GetRecordCount() <= 1)
                        //    goSingleRow = true;
                    }
                    //else if (wb != 0)
                    ////  workbench dynamic query for dependent windows
                    //{
                    //    query = _mWorkbench.GetQuery();
                    //}
                    //	Set initial Query on first tab
                    if (query != null)
                    {
                        gTab.SetQuery(query);
                    }
                    if (wb == 0)
                        _curTab = gTab;


                }	//	query on first tab

                //else
                //{
                //    windowTabs.Add(gTab);
                //}
                //        Component tabElement = null;
                Control tabElement = null;
                //        //  GridController
                if (gTab.IsSortTab())
                {
                    //VSortTab st = new VSortTab();
                    VSortTab st = new VSortTab(_curWindowNo, gTab.GetAD_Table_ID(),
                        gTab.GetAD_ColumnSortOrder_ID(), gTab.GetAD_ColumnSortYesNo_ID());
                    //st.setTabLevel(gTab.getTabLevel());
                    tabElement = st;
                }
                else	//	normal tab
                {
                    GridController gc = new GridController(true, true);
                    //            if (cc != null)
                    //              gc.setBackgroundColor(cc);                  //  set color on Window level
                    gc.InitGrid(gTab, false, _curWindowNo, this, mWindow);  //  will set color on Tab level
                    //                                                            //  Timing: ca. 6-7 sec for first .2 for next
                    //            gc.addDataStatusListener(this);
                    //            gc.registerESCAction(aIgnore);      //  register Escape Key

                    //Set Title of Tab

                    //gc.SetTabName(gTab.GetName());

                    //            //	Set First Tab
                    if (tab == 0)
                    {
                        _curGC = gc;
                        //Dimension size = gc.getPreferredSize();     //  Screen Sizing
                        //size.width += 4;
                        //size.height += 4;
                        //gc.setPreferredSize(size);
                    }
                    tabElement = gc;
                    //	If we have a zoom query, switch to single row
                    if (tab == 0 && goSingleRow)
                        gc.SwitchSingleRow();

                    //	Store GC if it has a included Tab
                    //if (gTab.GetIncluded_Tab_ID() != 0)
                    //    includedMap.Add(gTab.GetIncluded_Tab_ID(), gc);

                    //            //	Is this tab included?
                    //if (includedMap.Count > 0)
                    //{
                    //    //GridController parent = (GridController)includedMap[gTab.GetAD_Tab_ID()];
                    //    // if (parent != null)
                    //    // {
                    //    //    included = parent.includeTab(gc);
                    //    //                    if (!included)
                    //    //                        log.log(Level.SEVERE, "Not Included = " + gc);
                    //    //                }
                    //}
                }	//	normal tab

                if (!included)	//  Add to TabbedPane
                {
                    StringBuilder tabName = new StringBuilder();
                    tabName.Append("<html>");
                    if (gTab.IsReadOnly())
                        tabName.Append("<i>");
                    int pos = gTab.GetName().IndexOf(" ");
                    if (pos == -1)
                        tabName.Append(gTab.GetName()).Append("<br>&nbsp;");
                    else
                    {
                        tabName.Append(gTab.GetName().Substring(0, pos))
                          .Append("<br>")
                          .Append(gTab.GetName().Substring(pos + 1));
                    }
                    if (gTab.IsReadOnly())
                        tabName.Append("</i>");
                    tabName.Append("</html>");
                    //	Add Tab - sets ALT-<number> and Shift-ALT-<x>
                    //*
                    //tabElement.Text = tabName;
                    //TabPage tPage = new TabPage(gTab.GetName());//  tabName.ToString());
                    // tPage.Controls.Add(tabElement);
                    //*
                    window.AddTab(gTab.GetName(), gTab, tabElement);//  .Controls.Add(tPage);// .addTab (tabName.toString(), gTab, tabElement);
                    if (wb == 0 && tab == 0)
                    {

                        // ShowWindow();
                        //StateChanged(tabPanel,new SelectionChangedEventArgs( , new TabControlEventArgs(tabPanel.TabPages[0], 0, TabControlAction.Selected));
                        //Dimension size = gc.getPreferredSize();     //  Screen Sizing
                        //    //size.width += 4;
                        //    //size.height += 4;
                        //    //gc.setPreferredSize(size);
                    }
                }
            });
        }

        /// <summary>
        /// Load Event
        /// </summary>
        public void OnLoad()
        {
            List<MLookup> lookups = DataBase.DBQ.Get().GetWindowLookup(this._curWindowNo);
            if (lookups != null)
            {

                //new Thread(new ThreadStart(() =>
                //{
                for (int i = 0; i < lookups.Count; i++)
                {
                    lookups[i].InitializeSLOtherTabs();
                }
                DataBase.DBQ.Get().Dispose(_curWindowNo);
                //})).Start();
            }
        }

        /*Dispose */
        public void Dispose()
        {
            //if (_curAPanelTab != null)
            //{
            //    _curAPanelTab.UnRegisterVForm();
            //    _curAPanelTab = null;
            //}
            disposing = true;

            _curGC = null;
            _curTab = null;

            if (_mWorkbench != null)
            {
                for (int i = 0; i < _mWorkbench.GetWindowCount(); i++)
                {
                    _curWindowNo = _mWorkbench.GetWindowNo(i);
                    //log.Info("#" + _curWindowNo);
                    _ctx.SetAutoCommit(_curWindowNo, false);
                    _mWorkbench.Dispose(i);
                    _ctx.RemoveWindow(_curWindowNo);
                }
            }

            //  Get rid of remaining model
            if (_mWorkbench != null)
                _mWorkbench.Dispose();
            _mWorkbench = null;


            // tab Dispose

            if (tabPanel != null)
            {
                tabPanel.Dispose();
            }
            if (statusBar != null)
            {
                statusBar.Dispose();
            }
            statusBar = null;
        }

        /// <summary>
        /// Set current row postion
        /// </summary>
        /// <param name="row"></param>
        private void SetPosition(int row)
        {
            //SetButtonPressed(true);
            blockEvent = true;
            //currentBS.Position += row;
            _curGC.SetPostion(row);
            //this.BindingSource.Position = row;
            //SetButtonPressed(false);
            blockEvent = false;
            //SetNavigateButtons();
        }

        /// <summary>
        /// this function perform action when position of record is changed
        /// Called from "GridController class
        /// </summary>
        /// <returns></returns>
        public bool PositionChanging()
        {
            if (NeedSave(true))
            {
                if (SaveData(false))
                    return false;
                else
                {

                    return true;
                }
            }
            // SetNavigateButtons();
            // SetToolStripButtons();

            return false;
        }


        public void SetStatusLine(DataStatusEvent e)//   String text, Boolean error)
        {
            // log.Info(e.GetMessage());
            //String dbInfo = e.getMessage();
            String dbInfo = e.GetMessage();
            bool findPressed = _curTab.IsQueryActive() || _curTab.GetOnlyCurrentDays() > 0;
            if (findPressed)
                dbInfo = "[ " + dbInfo + " ]";
            statusBar.SetStatusDB(dbInfo, e);
            //lblRecord.Text = dbInfo;
            //	Set Message / Info
            if (e.GetAD_Message() != null || e.GetInfo() != null)
            {
                StringBuilder sb = new StringBuilder();
                String msg = e.GetMessage();
                if (msg != null && msg.Length > 0)
                    sb.Append(Utility.Msg.GetMsg(_ctx, e.GetAD_Message()));
                String info = e.GetInfo();
                if (info != null && info.Length > 0)
                {
                    if (sb.Length > 0 && !sb.ToString().Trim().EndsWith(":"))
                        sb.Append(": ");
                    sb.Append(info);
                }
                if (sb.Length > 0)
                {
                    int pos = sb.ToString().IndexOf("\n");
                    if (pos != -1)  // replace CR/NL
                        sb.Replace("\n", " - ", pos, 1);
                    statusBar.SetStatusLine(sb.ToString(), e.IsError());
                    //CommonFunctions.ShowMessage(sb.ToString(), statusBar, e.IsError());
                }
            }

            //  Confirm Error
            if (e.IsError() && !e.IsConfirmed())
            {
                //ADialog.error(m_curWindowNo, this, e.getAD_Message(), e.getInfo());
                ShowMessage.Error(e.GetAD_Message(), true, e.GetInfo());
                // MessageBox.Show(e.GetAD_Message() + "--" + e.GetInfo());
                e.SetConfirmed(true);   //  show just once - if MTable.setCurrentRow is involved the status event is re-issued
                //_errorDisplayed = true;
            }
            //  Confirm Warning
            else if (e.IsWarning() && !e.IsConfirmed())
            {
                //ADialog.warn(m_curWindowNo, this, e.getAD_Message(), e.getInfo());
                ShowMessage.Error(e.GetAD_Message(), true, e.GetInfo());
                //MessageBox.Show(e.GetAD_Message() + "--" + e.GetInfo());
                e.SetConfirmed(true);   //  show just once - if MTable.setCurrentRow is involved the status event is re-issued
            }
            //	update Change
            bool changed = e.IsChanged() || e.Isinserting();
            bool readOnly = _curTab.IsReadOnly();
            bool insertRecord = !readOnly;
            if (insertRecord)
                insertRecord = _curTab.IsInsertRecord();
            aNew.SetEnabled(!changed && insertRecord);
            aNewG.SetEnabled(!changed && insertRecord);
            aCopy.SetEnabled(!changed && insertRecord);
            aRefresh.SetEnabled(!changed);
            aDelete.SetEnabled(!changed && !readOnly);
            aDeleteSelection.SetEnabled(!changed && !readOnly && !_curGC.IsSingleRow());
            //
            if (readOnly && _curTab.IsAlwaysUpdateField())
                readOnly = false;
            aIgnore.SetEnabled(changed && !readOnly);
            aSave.SetEnabled(changed && !readOnly);
            //
            //	No Rows
            if (e.GetTotalRows() == 0 && insertRecord)
            {
                aNew.SetEnabled(true);
                aNewG.SetEnabled(true);
                aDelete.SetEnabled(false);
                aDeleteSelection.SetEnabled(false);
            }

            //	Single-Multi
            aMulti.SetPressed(!_curGC.IsSingleRow());

            //	History	or Query Active
            aFind.SetPressed(findPressed);

            //Transaction info
            if (_curTab.IsGetTrxInfo())
            {
                ThreadPool.QueueUserWorkItem(delegate
                {
                    if (_curTab != null)
                    {
                        string trxInfo = _curTab.GetTrxInfo();
                        if (trxInfo != null)
                            Dispatcher.BeginInvoke(delegate { if (statusBar == null) { return; } statusBar.SetInfo(trxInfo); });
                    }
                });
            }

            //if (trxInfo != null)
            //statusBar.SetInfo(trxInfo);


            //	Check Attachment
            bool canHaveAttachment = _curTab.CanHaveAttachment();		//	not single _ID column
            //
            //if (canHaveAttachment && e.isLoading() && m_curTab.getCurrentRow() > e.getLoadedRows())
            //  canHaveAttachment = false;
            if (canHaveAttachment && _curTab.GetRecord_ID() == -1)    //	No Key
                canHaveAttachment = false;
            if (canHaveAttachment)
            {
                aAttachment.SetEnabled(true);
                aAttachment.SetPressed(_curTab.HasAttachment());
                aChat.SetEnabled(true);
                aChat.SetPressed(_curTab.HasChat());

                aEmail.SetEnabled(true);
                aLetter.SetEnabled(true);
                aTask.SetEnabled(true);
                aFaxEMail.SetEnabled(true);
            }
            else
            {
                aAttachment.SetEnabled(false);
                aChat.SetEnabled(false);
                //aSubscribe.SetEnabled(false);
                //aMarkToExport.SetEnabled(true);
                //aMarkToExport.SetPressed(_curTab.HasExportRecord());
                aEmail.SetEnabled(false);
                aLetter.SetEnabled(false);
                aTask.SetEnabled(false);
                aFaxEMail.SetEnabled(false);
            }

            aSubscribe.SetEnabled(true);
            aSubscribe.SetPressed(_curTab.HasSubscribed());
            aMarkToExport.SetEnabled(true);
            aMarkToExport.SetPressed(_curTab.HasExportRecord());

            //----------------------------------------------------------------


            //if (_curTab.GetRecord_ID() != -1)
            //{

            //        Subscribe Subscribe = new Subscribe();
            //        bool isSubscribed = Subscribe.CheckSubscription(_curTab.GetAD_Window_ID(), _curTab.GetRecord_ID(), _curTab.GetAD_Table_ID()) == 0 ? false : true;
            //                               aSubscribe.SetPressed(isSubscribed);

            //}




            //----------------------------------------------------------------
            aAppointment.SetEnabled(aAttachment.IsEnabled() && MUser.GetIsEmployee(_ctx.GetAD_User_ID()) && !changed);

            //aLetter.SetEnabled(aAttachment.IsEnabled() && (aLetter.IsEnabled() || !changed) && _curTab.IsAllowLetter);
            //  aLetter.SetEnabled(aAttachment.IsEnabled() && aLetter.IsEnabled() && !changed);
            //  aEmail.SetEnabled(aAttachment.IsEnabled() && aEmail.IsEnabled() && !changed);
            //  aSms.SetEnabled(aAttachment.IsEnabled() && aSms.IsEnabled() && !changed);

            //	Lock Indicator 
            if (_isPersonalLock)
                aLock.SetPressed(_curTab.IsLocked());


            SetPageButtons(e._currentPage, e._totalPage);

            SetTreeViewItems();

            SetNavigateButtons();
            if (_curWinTab is VTabbedPane)
            {
                //if (!_curWinTab.InvokeRequired)
                //{
                ((VTabbedPane)_curWinTab).Evaluate(null);
                //}
            }
        }

        /// <summary>
        /// Remove/Clear TreeView Items on any change(event)
        /// </summary>
        private void SetTreeViewItems()
        {
            if (aRequest != null)
            {
                aRequest.GetTreeViewItem().Items.Clear();
            }

            if (aZoomAcross != null)
            {
                aZoomAcross.GetTreeViewItem().Items.Clear();
            }
        }

        private void SetPageButtons(int cPage, int tPage)
        {
            if (tPage < 2)
            {
                aPageDown.SetEnabled(false);
                aPageUp.SetEnabled(false);
                aPageLast.SetEnabled(false);
                aPageFirst.SetEnabled(false);
            }
            else if (cPage == tPage)
            {
                aPageDown.SetEnabled(false);
                aPageUp.SetEnabled(true);
                aPageLast.SetEnabled(false);
                aPageFirst.SetEnabled(true);
            }

            else if (cPage <= 1)
            {
                aPageDown.SetEnabled(true);
                aPageUp.SetEnabled(false);
                aPageLast.SetEnabled(true);
                aPageFirst.SetEnabled(false);
            }
            else
            {
                aPageDown.SetEnabled(true);
                aPageUp.SetEnabled(true);
                aPageLast.SetEnabled(true);
                aPageFirst.SetEnabled(true);
            }
            _curPage = cPage;
            _totalPage = tPage;
        }

        public void SetStatusLine(String text, Boolean error)
        {
            statusBar.SetStatusLine(text, error);
            //   CommonFunctions.ShowMessage(text, statusBar, error);
        }

        public void SetToolStripButtons()
        {
            if (_curTab == null)
            {
                return;
            }
            //	Check Attachment
            bool canHaveAttachment = _curTab.CanHaveAttachment();		//	not single _ID column
            //
            //if (canHaveAttachment && e.isLoading() && _curTab.getCurrentRow() > e.getLoadedRows())
            //    canHaveAttachment = false;
            if (canHaveAttachment && _curTab.GetRecord_ID() == -1)    //	No Key
                canHaveAttachment = false;
            if (canHaveAttachment)
            {
                aAttachment.SetEnabled(true);
                aAttachment.SetPressed(_curTab.HasAttachment());
                aChat.SetEnabled(true);
                aChat.SetPressed(_curTab.HasChat());
                aSubscribe.SetEnabled(true);
                aSubscribe.SetPressed(_curTab.HasSubscribed());
                //export
                //aMarkToExport.SetEnabled(true);
                //aMarkToExport.SetPressed(_curTab.HasExportRecord());
            }
            else
            {
                aAttachment.SetEnabled(false);
                aChat.SetEnabled(false);
                aSubscribe.SetEnabled(false);

                //aMarkToExport.SetEnabled(false);
            }

            //update by Karan
            aMarkToExport.SetEnabled(true);
            aMarkToExport.SetPressed(_curTab.HasExportRecord());


            //Updated by raghu
            if (_isPersonalLock)
            {
                aLock.SetPressed(_curTab.IsLocked());
            }
        }

        /// <summary>
        /// set DataProcessing buttons enable-disable eg, save,Delete,New,Cut,Paste
        /// </summary>
        /// <param name="value"></param>
        public void SetButtons(bool changed, bool isAddEnable)
        {
            //	update Change
            bool readOnly = _curTab.IsReadOnly();
            bool insertRecord = !readOnly;
            if (insertRecord)
                insertRecord = _curTab.IsInsertRecord();
            aNew.SetEnabled(isAddEnable && insertRecord);
            aNewG.SetEnabled(isAddEnable && insertRecord);
            aCopy.SetEnabled(!changed && insertRecord);
            aRefresh.SetEnabled(!changed);
            aDelete.SetEnabled(!changed && !readOnly);
            aDeleteSelection.SetEnabled(!changed && !readOnly && !_curGC.IsSingleRow());
            if (readOnly && _curTab.IsAlwaysUpdateField())// m_curTab.isAlwaysUpdateField())
                readOnly = false;
            aIgnore.SetEnabled(changed && !readOnly);
            aSave.SetEnabled(changed && !readOnly);
            //
            //	No Rows
            if (_curGC != null && _curTab.GetRowCount() == 0 && insertRecord)
            {
                aNew.SetEnabled(true);
                aNewG.SetEnabled(true);
                aDelete.SetEnabled(false);
                aDeleteSelection.SetEnabled(false);
            }

            //	Single-Multi
            aMulti.SetPressed(!_curGC.IsSingleRow());
            bool findPressed = _curTab.IsQueryActive() || _curTab.GetOnlyCurrentDays() > 0;
            //	History	or Query Active
            aFind.SetPressed(findPressed);
            //	Check Attachment
            bool canHaveAttachment = _curTab.CanHaveAttachment();		//	not single _ID column
            //
            //if (canHaveAttachment && e.isLoading() && m_curTab.getCurrentRow() > e.getLoadedRows())
            //  canHaveAttachment = false;
            if (canHaveAttachment && _curTab.GetRecord_ID() == -1)    //	No Key
                canHaveAttachment = false;
            if (canHaveAttachment)
            {
                aAttachment.SetEnabled(true);
                aAttachment.SetPressed(_curTab.HasAttachment());
                aChat.SetEnabled(true);
                aChat.SetPressed(_curTab.HasChat());
                aSubscribe.SetEnabled(true);
                aSubscribe.SetPressed(_curTab.HasSubscribed());


            }
            else
            {
                aAttachment.SetEnabled(false);
                aChat.SetEnabled(false);
                aSubscribe.SetEnabled(false);
            }

            aMarkToExport.SetEnabled(true);
            aMarkToExport.SetPressed(_curTab.HasExportRecord());

            //	Lock Indicator
            if (_isPersonalLock)
                aLock.SetPressed(_curTab.IsLocked());

        }

        /// <summary>
        /// Set navigations button(move records)
        /// </summary>
        public void SetNavigateButtons()
        {
            if (_curGC == null)
            {
                return;
            }
            int rows = _curTab.GetRowCount();

            if (rows - 1 > 0)
            {
                aFirst.SetEnabled(true);
                aPrevious.SetEnabled(true);

                aNext.SetEnabled(true);
                aLast.SetEnabled(true);
                if (_curTab.CurrentRow == 0)
                {
                    aFirst.SetEnabled(false);
                    aPrevious.SetEnabled(false);
                }
                if (_curTab.CurrentRow == rows - 1)
                {
                    aNext.SetEnabled(false);
                    aLast.SetEnabled(false);
                }
            }
            else
            {
                aFirst.SetEnabled(false);
                aPrevious.SetEnabled(false);
                aNext.SetEnabled(false);
                aLast.SetEnabled(false);
            }
        }

        private bool SaveData(bool manualSave)
        {
            //process focus field callout's
            _curGC.StopEditor(manualSave);
            SetBusy(true, true);
            string message = "";
            bool retValue = true;
            if (_curAPanelTab != null)
            {
                manualSave = false;
                _curAPanelTab.SaveData();
                aSave.SetEnabled(false);
                //SetBusy(false, false);
            }
            else
            {
                blockEvent = true;
                if (_curTab.GetCommitWarning().Trim().Length > 0 && NeedSave(true))
                {
                    ShowMessage.AskMessage("SaveChanges?", true, _curTab.GetCommitWarning()).Closed += (s, e) =>
                        {
                            if (((Message)s).DialogResult != null && ((Message)s).DialogResult.Value)
                            {
                                BackgroundWorker bgw = new BackgroundWorker();
                                bgw.DoWork += (sd, ed) =>
                                {
                                    ed.Result = _curGC.SaveData(manualSave);
                                };
                                bgw.RunWorkerCompleted += (sc, ec) =>
                                {
                                    bool rt = ec.Result == null ? false : (bool)ec.Result;
                                    _curGC.RowChanged(true, _curTab.GetRecord_ID());
                                    if (!manualSave)
                                    {
                                        _curGC.SetCurrentPostionData();
                                    }
                                    else if (manualSave)
                                    {
                                        _curGC.SetSelectedTreeNode();
                                    }
                                    AfterSave(rt, manualSave);
                                    bgw = null;
                                };
                                bgw.RunWorkerAsync();
                            }
                            else
                            {
                                bool retVal = false;
                                if (!manualSave)
                                {
                                    _curTab.CurrentRowDataObject.CancelEdit();// .Row.RejectChanges();
                                    _curGC.DynamicDisplay("");
                                    SetRowState(false, false);
                                    SetButtons(false, false);
                                    retVal = true;
                                }
                                SetBusy(false, true);
                                blockEvent = false;
                                // return retVal;
                            }
                        };


                    //if (MessageBox.Show("SaveChanges?" + _curTab.GetCommitWarning()) != MessageBoxResult.OK)
                    //{

                    //    bool retVal = false;
                    //    if (!manualSave)
                    //    {
                    //        _curTab.CurrentRowDataObject.CancelEdit();// .Row.RejectChanges();
                    //        _curGC.DynamicDisplay("");
                    //        SetRowState(false, false);
                    //        SetButtons(false, false);
                    //        retVal = true;
                    //    }
                    //    SetBusy(false, true);
                    //    blockEvent = false;
                    //    return retVal;
                    //}
                }
                else
                {

                    BackgroundWorker bgw = new BackgroundWorker();
                    bgw.DoWork += (sd, ed) =>
                    {
                        ed.Result = _curGC.SaveData(manualSave);
                    };
                    bgw.RunWorkerCompleted += (sc, ec) =>
                    {
                        bool rt = ec.Result == null ? false : (bool)ec.Result;
                        _curGC.RowChanged(true, _curTab.GetRecord_ID());
                        if (!manualSave)
                        {
                            _curGC.SetCurrentPostionData();
                        }
                        else if (manualSave)
                        {
                            _curGC.SetSelectedTreeNode();
                        }
                        AfterSave(rt, manualSave);
                        bgw = null;
                    };
                    bgw.RunWorkerAsync();
                }
            }
            return retValue;
        }

        public bool AfterSave(bool retValue, bool manualSave)
        {
            if (retValue)
            {
                //drvCurrent.Row.AcceptChanges();
                SetRowState(false, false);
                //this.BindingSource.EndEdit();
                if (manualSave)
                {
                    _curGC.DynamicDisplay("");
                }
                SetButtons(false, true);
            }
            else
            {
                //Navigate rows
                if (!manualSave)
                {
                    SetRowState(false, false);
                    SetButtons(false, true);
                }
                //tab selection change
                else
                {
                    //drvCurrent.Row.RejectChanges();
                }
            }

            if (mehtodinfo != null)
            {
                mehtodinfo.Invoke(this, arguments.ToArray());
            }


            mehtodinfo = null;
            arguments.Clear();

            blockEvent = false;


            if (actionProcessAfterSave != null)
            {
                if (retValue)
                {
                    actionProcessAfterSave.Invoke();
                }

                actionProcessAfterSave = null;

            }

            SetBusy(false, true);

            //if (NeedSave())
            //{
            //    if (_curTab.GetCommitWarning().Trim().Length > 0)
            //{
            //    if (!ShowMessage.Ask("SaveChanges?", true, _curTab.GetCommitWarning()))
            //    {
            //        blockEvent = false;
            //        return false;
            //    }
            //}

            //    //if (ShowMessage.Ask("save", null, "Want to Save Data"))
            //    //{
            //    if (gridVisible)
            //    {
            //        _curTab.GridPanal.EndEdit();
            //    }
            //    else
            //    {
            //        this.BindingSource.EndEdit();
            //    }
            //_curGC.StopEditor(true);
            // blockEvent = true;
            //    _curTab.FieldPanal.Parent.Select();

            //  retValue = _curTab.DataSave(manualSave, drvCurrent);

            return retValue;
        }

        public bool NeedSave(bool checkNew)
        {
            //if (!isCurentRowDirty)
            //{
            //    if (_curTab.NeedSave(true, false))
            //    {
            //        isCurentRowDirty = true;
            //    }
            //}
            bool retvalue = isCurentRowDirty || (_curTab != null && _curTab.IsRowDirty);

            if (!retvalue && checkNew)
            {
                retvalue = newRow;
            }
            return retvalue;
        }

        /// <summary>
        /// Set Row state flag --- editing or commit
        /// </summary>
        /// <param name="rowDirty"></param>
        /// <param name="isNewRow"></param>
        private void SetRowState(bool rowDirty, bool isNewRow)
        {
            isCurentRowDirty = rowDirty;
            newRow = isNewRow;
            _curTab.IsRowDirty = rowDirty;
        }

        /// <summary>
        /// Add New Row to Datasource
        /// </summary>
        public void AddNewRow(bool copy)
        {
            blockEvent = true;
            newRow = true;
            //this.Cursor = Cursors.Wait;
            _curGC.AddNewRow(copy);
        }

        public void AfterAddNewRow(bool isAdded)
        {
            if (isAdded)
            {
                SetRowState(false, true);
                SetNavigateButtons();
            }
            else
            {
                SetRowState(false, false);
            }
            _curGC.DynamicDisplay("");
            //this.Cursor = Cursors.Arrow;
            SetBusy(false, true);
            blockEvent = false;
        }

        /// <summary>
        /// Refresh Only Current Row
        /// </summary>
        private void DataRowRefresh(bool refreshUi, ProcessInfo pi)
        {
            //Disable callout
            blockEvent = true;


            BackgroundWorker bgw = new BackgroundWorker();

            bgw.DoWork += (ds, dc) =>
                {
                    _curGC.DataRefreshRow();

                };

            bgw.RunWorkerCompleted += (cs, ce) =>
                {
                    if (pi != null)
                    {
                        Dispatcher.BeginInvoke(() =>
                        SetStatusLine(pi.GetSummary(), pi.IsError()));
                    }

                    if (Dispatcher.CheckAccess())
                    {
                        if (refreshUi)
                        {
                            _curGC.DynamicDisplay("");
                        }

                        SetBusy(false, false);
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(delegate
                        {
                            if (refreshUi)
                            {
                                _curGC.DynamicDisplay("");
                            }

                            SetBusy(false, false);
                        });
                    }

                    blockEvent = false;
                };
            bgw.RunWorkerAsync();
        }

        /// <summary>
        ///Indicate Busy
        /// </summary>
        /// <param name="busy">is busy </param>
        /// <param name="focus">is focus</param>
        /// 
        SilverlightDesktop.Controls.Form frame = null;
        public void SetBusy(bool busy, bool focus)
        {
            SetBusy(busy, focus, null);

            ////_isLocked = busy;
            ////
            //if (frame == null)
            //{
            //    frame = VAdvantage.Utility.Envs.GetForm(this);
            //}
            //if (frame == null)  //  during init
            //    return;
            ////if (frame is AWindow)
            ////frame.Cursor = Cursors.WaitCursor;  //((AWindow)frame).setBusy(busy);
            //String processing = Msg.GetMsg(_ctx, "Processing");

            //SetBusyGrid(busy, processing);
            //if (busy)
            //{

            //    //busyGrid.Visibility = System.Windows.Visibility.Visible;
            //    SetStatusLine(processing, false);
            //    this.Cursor = Cursors.Wait;
            //    //toolBar.IsReadOnly = true;
            //    //this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            //    frame.Cursor = Cursors.Wait;// .setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            //}
            //else
            //{

            //    this.Cursor = Cursors.Arrow;
            //    // toolBar.IsReadOnly = false;
            //    //this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            //    frame.Cursor = Cursors.Arrow;// .setCursor(Cursor.getPredefi
            //    if (focus)
            //    {
            //        //_curGC.Focus();
            //        _curGC.RequestFocusInWindow();
            //    }
            //    if (statusBar.GetStatusLine().Equals(processing))
            //    {
            //        statusBar.SetStatusLine("");
            //    }
            //    //if (lblStatusMsg.Text.Equals(processing))
            //    //	lblStatusMsg.Text = "";// .setStatusLine("");
            //}
        }

        public void SetBusy(bool busy, bool focus, string msg)
        {
            SetBusy(busy, focus, msg, null);
        }

        public void SetBusy(bool busy, bool focus, string msg, string statusMess)
        {

            if (!Dispatcher.CheckAccess())
            {
                return;
            }

            //_isLocked = busy;
            //
            if (frame == null)
            {
                frame = VAdvantage.Utility.Envs.GetForm(this);
            }
            if (frame == null)  //  during init
                return;
            //if (frame is AWindow)
            //frame.Cursor = Cursors.WaitCursor;  //((AWindow)frame).setBusy(busy);
            String processing = Msg.GetMsg(_ctx, "Processing");

            if (msg == null || msg.Trim().Length < 1)
            {
                SetBusyGrid(busy, processing);
            }
            else
            {
                String m = Msg.GetMsg(_ctx, msg);
                //String m = msg;
                SetBusyGrid(busy, m);
            }
            if (busy)
            {

                //busyGrid.Visibility = System.Windows.Visibility.Visible;
                SetStatusLine(processing, false);
                this.Cursor = Cursors.Wait;
                //toolBar.IsReadOnly = true;
                //this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                frame.Cursor = Cursors.Wait;// .setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            }
            else
            {

                this.Cursor = Cursors.Arrow;
                // toolBar.IsReadOnly = false;
                //this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                frame.Cursor = Cursors.Arrow;// .setCursor(Cursor.getPredefi
                if (focus)
                {
                    //_curGC.Focus();
                    _curGC.RequestFocusInWindow();
                }
                if (statusMess != null)
                {
                    statusBar.SetStatusLine(statusMess);
                }
                if (statusBar.GetStatusLine().Equals(processing))
                {
                    statusBar.SetStatusLine("");
                }
                //if (lblStatusMsg.Text.Equals(processing))
                //	lblStatusMsg.Text = "";// .setStatusLine("");
            }
        }

        private void SetBusyGrid(bool busy, String text)
        {
            busyGrid.Visibility = busy ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            busyMessage.Visibility = busy ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;


            if (busy)
            {
                busyMessage.Text = text;
            }
            else
            {
                busyMessage.Text = "";
            }

        }

        /// <summary>
        /// Get Window Index
        /// </summary>
        /// <returns></returns>
        private int GetWindowIndex()
        {
            //  only one window
            if (_mWorkbench.GetWindowCount() == 1)
                return 0;
            //  workbench
            return tabPanel.SelectedIndex;
        }

        #endregion

        #region EventHandler

        public void ValueChanged(object sender, EventArgs e)
        {
            if (blockEvent || disposing)
                return;


            if (!_curGC.IsSingleRow())// || isButtonPressed)
            {
                return;
            }


            IControl ctrl = (IControl)sender;

            if (!ctrl.Focused)
            {
                return;
            }

            if (ctrl.GetIsReadonly())
            {
                ctrl = null;
                return;
            }
            if (_curTab.CurrentRowDataObject == null)
            {
                ctrl.SetReadOnly(true);
                ctrl = null;
                return;
            }


            if (Utility.Util.IsEqual(_curTab.CurrentRowDataObject.GetFieldValue(ctrl.GetName().ToUpper()), ctrl.GetValue()))

            //            if (_curTab.CurrentRowDataObject.GetFieldValue(ctrl.GetName().ToUpper()).Equals(ctrl.GetValue()))
            {

                if (DisplayType.IsDate(ctrl.GetDisplayType()))
                    return;
            }


            GridField field = ctrl.GetField();
            _curGC.SetValueChanged();

            field.SetValue(ctrl.GetValue(), _curTab.GetTableObj().IsInserting());

            blockEvent = true;

            //TimeSpan dt1 = DateTime.Now.TimeOfDay;
            //if (DisplayType.IsNumeric(field.GetDisplayType()))
            //{
            //    _curTab.CurrentRowData[ctrl.GetName()] = decimal.Parse(ctrl.GetValue().ToString() , System.Globalization.CultureInfo.GetCultureInfo("en-US").NumberFormat);
            //}
            //else
            //{

            _curTab.CurrentRowDataObject.SetFieldValue(ctrl.GetName().ToUpper(), ctrl.GetValue());



            //ctrl = null;
            blockEvent = false;

            if (!isCurentRowDirty)
            {
                isCurentRowDirty = true;
                //SetButtons(true, false);
            }
            blockEvent = false;


            if (_curTab.FieldHasCallOut(field))
            {
                SetBusy(true, false, "Processing Callout....");
                ThreadPool.QueueUserWorkItem(delegate
                {
                    System.Globalization.CultureInfo culture = Login.Language.GetLoginLanguage().GetCulture();//  language.GetCulture();
                    System.Threading.Thread.CurrentThread.CurrentCulture = culture;
                    System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
                    blockEvent = true;
                    if (_curTab.ProcessDependentAndCallOut(field))
                    {
                        //_curTab.CurrentRowData.EndEdit();
                        //  TimeSpan dt2 = DateTime.Now.TimeOfDay;
                        //  MessageBox.Show((dt2 - dt1).ToString());
                        //((DataRowView)this.BindingSource.Current)
                        //this.BindingSource.EndEdit();
                        // this.BindingSource.ResetCurrentItem();
                        Dispatcher.BeginInvoke(delegate
                        {
                            EndValueChanged(ctrl);

                        });
                    }
                    else
                    {
                        // _curTab.CurrentRowData.EndEdit();
                        // if (sender is Grids.VComboBox || sender is Controls.VCheckBox)
                        //{
                        Dispatcher.BeginInvoke(delegate
                        {
                            EndValueChanged(ctrl);
                        });
                    }
                    blockEvent = false;
                });
            }
            else
            {
                if (sender is Controls.VComboBox || sender is Controls.VCheckBox)
                {
                    EndValueChanged(ctrl);
                }
                //SetBusy(false, true);
                blockEvent = false;
            }
        }

        private void EndValueChanged(IControl ctrl)
        {
            _curGC.DynamicDisplay("");
            SetBusy(false);
            //   if (ctrl is VTextBoxButton && ctrl.GetName().Equals("M_Product_ID") && (((VTextBoxButton)(ctrl)).multipleSelection))
            if (ctrl is VTextBoxButton && ctrl.GetName().Equals("M_Product_ID") && (((VTextBoxButton)(ctrl)).multipleSelection) && !(((VTextBoxButton)(ctrl)).updating))
            {
                if (Util.GetValueOfString(Envs.GetCtx().GetContext("Single")) != "Y")
                //if (!single)
                {
                    // SaveMultipleRecord(((VTextBoxButton)ctrl).InfoMulipleIds, ctrl.GetName());
                    ((VTextBoxButton)ctrl).InfoMulipleIds = null;
                    Cmd_RefreshAfterSave();
                }
            }
            Envs.GetCtx().SetContext("Single", false);
        }

        private void SaveMultipleRecord(object[] newValues, string colName)
        {
            if (newValues == null || newValues.Length < 1)
                return;
            SetBusy(true);
            _curTab.GetTableObj().isMultipleProduct = true;
            MultiSaveHelper helper = new MultiSaveHelper(_curGC, _curTab, newValues, colName);
            helper.Completed += (s, e) =>
            {
                _curTab.GetTableObj().isMultipleProduct = false;

                if (((CompletedEventArgs)e).Completed)
                {
                    AfterSave(true, false);
                    SetBusy(true, false, "Refresh");
                    Cmd_RefreshAfterSave();
                    // DataRefreshAll();
                }
                else
                {
                    SetBusy(false, true);
                }

                helper = null;
            };
            helper.Start();
        }

        /// <summary>
        /// fired when control text is changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void FireTextChanged(object sender, EventArgs e)
        {
            if (blockEvent)
            { return; }
            if (!_curGC.IsSingleRow() || !((IControl)sender).Focused)// || isButtonPressed)
            {
                return;
            }
            if (!isCurentRowDirty)
            {
                isCurentRowDirty = true;
                _curGC.SetValueChanged();
            }
        }


        public void CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (!blockEvent)
            {
                _curGC.SetValueChanged();
                isCurentRowDirty = true;
            }
        }

        void StateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (disposing)
            {
                return;
            }

            SetBusy(true, false);
            blockEvent = true; //block events of controls


            VTabbedPane tp = (VTabbedPane)sender;
            bool back = false;
            bool isAPanelTab = false;

            //  Workbench Tab Change
            if (tp.IsWorkbench())
            {
                int WBIndex = tabPanel.SelectedIndex; // .getSelectedIndex();
                _curWindowNo = _mWorkbench.GetWindowNo(WBIndex);
                //  Window Change
                log.Info("curWin=" + _curWindowNo + " - Win=" + tp);
                if (((TabItem)tp.SelectedItem).Content is Controls.VTabControl)
                    _curWinTab = (Controls.VTabControl)((TabItem)tp.SelectedItem).Content;
                else
                    throw new ArgumentException("Window does not contain Tabs");
                if (((TabItem)_curWinTab.SelectedItem).Content is GridController)
                    _curGC = (GridController)((TabItem)_curWinTab.SelectedItem).Content;
                //	else if (m_curWinTab.getSelectedComponent() instanceof APanelTab)
                //		isAPanelTab = true;
                else
                    throw new ArgumentException("Window-Tab does not contain GridControler");
                //  change pointers
                _curTabIndex = _curWinTab.SelectedIndex;
            }


            else
            {
                //  Just a Tab Change
                //log.Info("Tab=" + tp);
                _curWinTab = tp;
                int tpIndex = _curWinTab.SelectedIndex;
                back = tpIndex < _curTabIndex;
                GridController gc = null;
                if (((TabItem)_curWinTab.SelectedItem).Content is GridController)
                    gc = (GridController)((TabItem)_curWinTab.SelectedItem).Content;
                else if (((TabItem)_curWinTab.SelectedItem).Content is VSortTab)
                    isAPanelTab = true;
                else
                    throw new ArgumentException("Tab does not contain GridControler");
                //  Save old Tab
                if (_curGC != null)
                {
                    ////  has anything changed?
                    if (NeedSave(false))
                    {
                        bool isAutoCommit = _ctx.IsAutoCommit(_curWindowNo);
                        //        Automatic Save
                        if (isAutoCommit)
                        {
                            //    //if (!tabOld.DataSave(false))//, drvCurrent))

                            ThreadPool.QueueUserWorkItem(delegate
                            {
                                bool saved = _curGC.SaveData(true);//  SaveData(true,false))

                                Dispatcher.BeginInvoke(delegate
                                {
                                    if (!saved)
                                    {
                                        _curWinTab.SelectedIndex = _curTabIndex;
                                        SetBusy(false, true);
                                        _curTab.CurrentRowDataObject.EndEdit();
                                        _curGC.DynamicDisplay("");
                                        blockEvent = false;
                                        //e.Cancel = true;
                                        return;
                                    }

                                    else
                                    {
                                        SetRowState(false, false);
                                        StateChanged(sender, e);
                                    }

                                });
                            });
                            return;

                            //    {

                        }
                        else if (!isAutoCommit)
                        {
                            ShowMessage.AskMessage("SaveChanges?", true, _curTab.GetCommitWarning()).Closed += (sa, ea) =>
                                {
                                    if (true.Equals(((Message)sa).DialogResult))
                                    {
                                        ThreadPool.QueueUserWorkItem(delegate
                                        {
                                            bool saved = _curGC.SaveData(true);

                                            Dispatcher.BeginInvoke(delegate
                                            {
                                                if (!saved)//, drvCurrent))
                                                {
                                                    _curWinTab.SelectedIndex = _curTabIndex;
                                                    SetBusy(false, true);
                                                    //e.Cancel = true;
                                                    _curTab.CurrentRowDataObject.EndEdit();
                                                    blockEvent = false;
                                                    return;
                                                }
                                                else
                                                {

                                                    SetRowState(false, false);
                                                    StateChanged(sender, e);
                                                }

                                            });
                                        });
                                    }
                                    else
                                    {
                                        _curTab.DataIgnore();
                                        SetRowState(false, false);
                                        StateChanged(sender, e);
                                    }
                                };
                            return;
                        }

                        else
                        {
                            _curTab.DataIgnore();
                        }

                        SetRowState(false, false);
                    }


                    if (newRow && _curGC.RowCount() <= 1)
                    {
                        newRow = false;
                    }
                }

                //this.toolBar.BindingSource = null;
                // currentBS = null;

                if (_curAPanelTab != null)
                {
                    _curAPanelTab.SaveData();
                    _curAPanelTab.UnRegisterVForm();
                    _curAPanelTab = null;
                }

                //	new tab
                //	if (m_curTabIndex >= 0)
                //		m_curWinTab.setForegroundAt(m_curTabIndex, ViennaPLAF.getTextColor_Normal());
                //	m_curWinTab.setForegroundAt(tpIndex, ViennaPLAF.getTextColor_OK());
                _curTabIndex = tpIndex;
                if (!isAPanelTab)
                    _curGC = gc;
            }

            PopulateSerachCombo(true);

            bool parentValid = true;
            if (isAPanelTab)
            {
                _curAPanelTab = (VSortTab)((TabItem)_curWinTab.SelectedItem).Content;
                _curAPanelTab.RegisterVForm(this);
                _curAPanelTab.LoadData();
                ShowWindow();
                SetButtons(false, false);
                SetBusy(false, true);
            }
            else
            {
                // _curGC = (Grids.GridController)_curWinTab.SelectedTab.Controls[0];
                _curGC.Activate();
                _curTab = _curGC.GetMTab();
                PopulateSerachCombo(false);
                //	Refresh only current row when tab is current(parent)
                if (back && _curTab.IsCurrent())
                {
                    // BindDataSet(); 
                    DataRowRefresh(false, null);
                    //SetBusy(false, true);
                    //_curTab.DataRefresh();
                    //PerformInitialAction(true);
                    // SetButtons(false, true);
                }
                else	//	Requery and bind
                {

                    if (true)
                    {
                        MRole role = MRole.GetDefault();

                        _curTab.GetTableObj().SetCurrentPage(1);

                        _curGC.query(_curTab.GetOnlyCurrentDays(),
                             role.GetMaxQueryRecords(), false);	//	updated
                    }
                    else
                    {
                        if (_curWinTab is VTabbedPane)
                            ((VTabbedPane)_curWinTab).Evaluate(null);
                        SetNavigateButtons();
                        SetButtons(false, false);
                        aNew.SetEnabled(false);
                        aNewG.SetEnabled(false);
                        aDelete.SetEnabled(false);
                        aDeleteSelection.SetEnabled(false);
                        _curGC.DynamicDisplay("");
                        SetBusy(false, true);
                    }
                }
            }

            //currentBS = _curGC.GetDataSource();
            //this.toolBar.BindingSource = currentBS;


            // else //set context evry time, either bindingsource contain data or add new row or parentcolumn is not valid.
            //  {
            //_curGC.SetCurrentRowData();
            //SetNavigateButtons();
            //SetButtons(false, true);
            //}

            //	Update <-> Navigation
            // aDetail.SetEnabled(_curTabIndex != _curWinTab.TabCount - 1);
            // aParent.SetEnabled(_curTabIndex != 0 && _curWinTab.TabCount > 1);

            //	Document Print
            aPrint.SetEnabled(_curTab.IsPrinted());
            //	Query
            bool findPressed = _curTab.IsQueryActive() || _curTab.GetOnlyCurrentDays() > 0;
            aFind.SetPressed(findPressed);


            //if (printFormat != null)
            //{
            //    for (int c = 0; c < printFormat.Items.Count; c++)
            //    {
            //        printFormat.RemoveAt(0);
            //        c--;
            //    }
            //    if (printFormat.Triggers.Count > 0)
            //        printFormat.Triggers.RemoveAt(0);

            //    PopupMenuManager.UnregisterMenu(printFormat);
            //    printFormat = null;
            //}

            //SetNavigateButtons();

            //ThreadPool.QueueUserWorkItem(delegate
            //{
            //    _list.Clear();


            //    CreatePrintFormat(_curTab.GetAD_Table_ID());

            //    if (_list.Count > 0)
            //    {
            //        Dispatcher.BeginInvoke(delegate
            //        {


            //            if (printFormat == null)
            //                printFormat = new PopupMenu();
            //            for (int i = 0; i <= _list.Count - 1; i++)
            //            {
            //                PopupMenuItem reportmnu = new PopupMenuItem(null, _list[i].GetName(), null);
            //                reportmnu.Click += (ov, ev) =>
            //                    {
            //                        clickedMenu = (ov as PopupMenuItem).Header.ToString();
            //                        Cmd_Report();
            //                    };
            //                printFormat.AddItem(reportmnu);
            //            }

            //            printFormat.AddTrigger(TriggerTypes.LeftClick, aReport.GetButton());

            //        });
            //    }
            //    else
            //    {
            //        clickedMenu = "";
            //        Dispatcher.BeginInvoke(delegate
            //        {
            //            aReport.GetButton().Click +=new RoutedEventHandler(APanel_Click);
            //        });
            //    }
            //});

            //	Order Tab
            if (isAPanelTab)
            {
                aMulti.SetPressed(false);
                aMulti.SetEnabled(false);
                aNew.SetEnabled(false);
                aNewG.SetEnabled(false);
                aDelete.SetEnabled(false);
                aDeleteSelection.SetEnabled(false);
                aFind.SetEnabled(false);
                aRefresh.SetEnabled(false);
                aAttachment.SetEnabled(false);
                aChat.SetEnabled(false);
                aMarkToExport.SetEnabled(false);
                aSubscribe.SetEnabled(false);
                // aLetter.SetEnabled(false);
                aAppointment.SetEnabled(false);
                // aSms.SetEnabled(false);
                // aEmail.SetEnabled(false);
                aImportMap.SetEnabled(false);
            }
            else	//	Grid Tab
            {
                aMulti.SetEnabled(true);
                aMulti.SetPressed(!_curGC.IsSingleRow());
                aFind.SetEnabled(true);
                aRefresh.SetEnabled(true);
                aAttachment.SetEnabled(true);
                aChat.SetEnabled(true);
                aMarkToExport.SetEnabled(true);
                aLetter.SetEnabled(true);
                aAppointment.SetEnabled(true);
                aSms.SetEnabled(true);
                aEmail.SetEnabled(true);
                aFaxEMail.SetEnabled(true);
                aImportMap.SetEnabled(true);
                aSubscribe.SetEnabled(true);
            }

            ////
            ////_curWinTab.requestFocusInWindow();

            // blockEvent = true;
            // _curWinTab.SelectedTab.Show();
            if (!isAPanelTab)
            {

                //_curGC.DynamicDisplay("");
            }
            blockEvent = false;
            //_curWinTab.Focus();
            // 
            // log.Config("finish");
        }


        private void PopulateSerachCombo(bool isClear)
        {
            cmbSearch.SelectionChanged -= new SelectionChangedEventHandler(cmbSearch_SelectionChanged);
            if (isClear)
            {
                cmbSearch.Items.Clear();
            }
            else
            {
                cmbSearch.IsEnabled = false;

                var client = AEnv.GetDataServiceDBClient();

                client.GetDataXMLCompleted += (s, e) =>
                    {
                        if (e.Error != null)
                        {

                        }
                        else if (e.ServiceError != null)
                        {

                        }
                        else
                        {
                            System.Xml.Linq.XElement data = System.Xml.Linq.XElement.Parse(e.Result);

                            //var list = from t in data.Descendants("Table")
                            //           select t;

                            var list = data.Descendants("Table");

                            foreach (var dr in list)
                            {
                                ValueNamePair knp = new ValueNamePair(Util.GetValueofString(dr, "Code"), Util.GetValueofString(dr, "Name"));
                                cmbSearch.Items.Add(knp);
                            }

                            cmbSearch.IsEnabled = true;

                            if (cmbSearch.Items.Count > 0)
                            {
                                cmbSearch.Items.Insert(0, new ValueNamePair(" ", Msg.GetMsg(_ctx, "All")));
                                cmbSearch.SelectionChanged += new SelectionChangedEventHandler(cmbSearch_SelectionChanged);
                            }
                        }
                    };

                int AD_Client_ID = _ctx.GetAD_Client_ID();
                DataSet ds = null;
                string sql = "SELECT NAME,Code FROM AD_UserQuery WHERE"
                    + " AD_Client_ID=" + AD_Client_ID + " AND IsActive='Y'"
                    + " AND (AD_Tab_ID=" + _curTab.GetAD_Tab_ID() + " OR AD_Table_ID=" + _curTab.GetAD_Table_ID() + ")"
                    + " ORDER BY AD_UserQuery_ID";


                client.GetDataXMLAsync(sql, null, null);
                client.CloseAsync();


                SetDynamicAcionPane();
                //int count =5;
            }

        }

        private void SetDynamicAcionPane()
        {
            if (_curGC == null)
                return;

            /* Clear Previous */

            if (lstAction.Items.Count > actionItemCount_Left)
            {
                while (lstAction.Items.Count > actionItemCount_Left)
                {
                    lstAction.Items.RemoveAt(0);
                }
            }

            if (lstRelated.Items.Count > actionItemCount_Right)
            {
                while (lstRelated.Items.Count > actionItemCount_Left)
                {
                    lstRelated.Items.RemoveAt(0);
                }
            }
            /*end */

            _curGC.TreePaneLeftLinks = lstAction;
            _curGC.TreePaneRightLinks = lstRelated;

            int index = 0;
            if (_curGC.leftPaneLinkItems.Count > 0)
            {
                foreach (object o in _curGC.leftPaneLinkItems)
                {
                    lstAction.Items.Insert(index, o);
                    index++;
                }
            }
            index = 0;
            if (_curGC.rightPaneLinkItems.Count > 0)
            {
                foreach (object o in _curGC.rightPaneLinkItems)
                {
                    lstRelated.Items.Insert(index, o);
                    index++;
                }
            }

            if (lstAction.Items.Count > 0)
            {
                actionItem.IsSelected = true;
            }
            else
            {
                historyItem.IsSelected = true;
            }
        }

        void cmbSearch_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbSearch.SelectedIndex == -1 || cmbSearch.SelectedItem == null)
            {
                return;
            }

            if (cmbSearch.SelectedItem != null)
            {
                ValueNamePair value = cmbSearch.SelectedItem as ValueNamePair;
                SetBusy(true, false);
                Query query = new Query(_curTab.GetTableName());
                query.AddRestriction(value.GetValue());

                int no = 0;
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    no = GetNoOfRecords(query, true);

                    if (no < 1)
                    {
                        return;
                    }
                    //_query.SetRecordCount(no);

                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {
                        SetBusy(false, true);
                        int onlyCurrentDays = 0;
                        //bool created = find.GetIsCreated();
                        //find = null;
                        //Stop callout
                        blockEvent = true;
                        //	Confirmed query
                        //Set Page value to 1
                        _curTab.GetTableObj().SetCurrentPage(1);
                        if (query != null && query.IsActive())
                        {
                            //log.config(query.toString());
                            _curTab.SetQuery(query);
                            _curGC.query(0, 0, false);   //  autoSize
                        }
                        else
                        {
                            int maxRows = MRole.GetDefault().GetMaxQueryRecords();
                            //log.config("OnlyCurrentDays=" + onlyCurrentDays + ", MaxRows=" + maxRows);
                            _curTab.SetQuery(null);	//	reset previous queries
                            _curGC.query(onlyCurrentDays, maxRows, false);   //  autoSize
                        }

                        bool findPressed = _curTab.IsQueryActive() || _curTab.GetOnlyCurrentDays() > 0;
                        aFind.SetPressed(findPressed);
                        _curGC.DynamicDisplay("");
                        SetNavigateButtons();
                        SetToolStripButtons();
                        SetRowState(false, false);
                    });
                });
            }
        }

        private int GetNoOfRecords(Query query, bool alertZeroRecords)
        {
            // make query
            StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM ");
            sql.Append(_curTab.GetTableName());
            bool hasWhere = false;
            // add where clause if already exists
            if (_curTab.GetWhereExtended() != null && _curTab.GetWhereExtended().Length > 0)
            {
                string where = _curTab.GetWhereExtended();

                if (where.IndexOf("@") != -1)
                {
                    where = Envs.ParseContext(_ctx, _curWindowNo, where, false);
                }

                sql.Append(" WHERE ").Append(where);
                hasWhere = true;
            }
            // if user has given any query
            if (query != null && query.IsActive())
            {
                // if where clause is started, then add "AND"
                if (hasWhere)
                {
                    sql.Append(" AND ");
                }
                // add "WHERE"
                else
                {
                    sql.Append(" WHERE ");
                }
                sql.Append(query.GetWhereClause());
            }
            //	Add Access
            string finalSQL = MRole.GetDefault().AddAccessSQL(sql.ToString(), _curTab.GetTableName(),
                MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
            //finalSQL = Env.ParseContext(_ctx, _targetWindowNo, finalSQL, false);

            //_ctx.SetContext(_targetWindowNo, TABNO, "FindSQL", finalSQL);

            //  Execute Query
            int _total = 0;

            //System.Threading.ThreadPool.QueueUserWorkItem(delegate
            //{
            //    try
            //    {
            //        _total = int.Parse(ExecuteQuery.ExecuteScalar(finalSQL));
            //        _total = DataBase.DB.GetSQLValue(null, finalSQL, null);
            //    }
            //    catch (Exception ex)
            //    {
            //        log.Log(Level.SEVERE, finalSQL, ex);
            //    }
            //    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => GetTotal(_total, query, alertZeroRecords));

            //});
            try
            {

                //_total = int.Parse(ExecuteQuery.ExecuteScalar(finalSQL));

                _total = DataBase.DB.GetSQLValue(null, finalSQL, null);
            }
            catch (Exception ex)
            {
                log.Log(Level.SEVERE, finalSQL, ex);
            }
            MRole role = MRole.GetDefault();
            //	No Records
            if (_total == 0)
            {
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                {

                    ShowMessage.Info("FindZeroRecords", true, "", null);
                    cmbSearch.SelectedIndex = -1;
                    SetBusy(false, false);
                    //TotalCheck(alertZeroRecords));   

                });
            }
            //	More then allowed
            else if (query != null && role.IsQueryMax(_total))
            {
                ShowMessage.Error("FindOverMax", true, _total + " > " + role.GetMaxQueryRecords());//silverlight
                SetBusy(false, false);
                //MessageBox.Show("FindZeroRecords " + _total + " > " + role.GetMaxQueryRecords());
            }
            else
            {
                //_isOkPressed = true;
                log.Config("#" + _total);
            }
            // show query's where clause on status bar
            if (query != null)
            {
                //CommonFunctions.ShowMessage(query.GetWhereClause(), lblStatusBar);
            }
            return _total;
        }

        void APanel_Click(object sender, RoutedEventArgs e)
        {
            Cmd_Report();
        }

        string clickedMenu = null;
        public bool loading = true;
        bool _lookupPending = true;
        public void ShowWindow()
        {
            if (!loading)
            { return; }
            loading = false;
            windowHost.ShowWindow();
            Utility.Envs.SetBusyIndicator(false);
        }
        /// <summary>
        /// handler menu and tool bar event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ActionPerformed(object sender, RoutedEventArgs e)
        {
            string cmd = "";
            if (sender is IActionName)
            {
                cmd = ((IActionName)sender).ActionName;
            }
            //else if (sender is ToolStripMenuItem)
            //{
            //    cmd = ((ToolStripMenuItem)sender).Name;
            //}
            //log.Info(cmd + " - " + Control.ModifierKeys);
            // _lastModifiers = (int)(ModifierKeys.Control);
            _lastModifiers = (int)(Keyboard.Modifiers);

            //	+ " - " + new Timestamp(e.getWhen()) + " " + isUILocked());
            if (disposing || _isLocked)
                return;

            //String cmd = e.getActionCommand();
            //	Do ScreenShot w/o busy
            if (cmd.Equals("ScreenShot"))
            {
                //AEnv.actionPerformed (e.getActionCommand(), m_curWindowNo, this);
                return;
            }

            //  Problem: doubleClick detection - can't disable button as clicking button may change button status
            SetBusy(true, false);
            //  Command Buttons
            //if (sender instanceof VButton)
            //{
            //    actionButton((VButton)e.getSource());
            //    setBusy(false, true);
            //    return;
            //}

            try
            {
                //	File
                if (cmd.Equals(aFirst.GetName()))
                {	/*cmd_save(false);*/
                    SetPosition(0);
                    if (NeedSave(false))
                    {
                        return;
                    }

                    //m_curGC.getTable().removeEditor();
                    //m_curTab.navigate(0);
                    //m_curGC.requestFocusInWindow();
                }
                else if (cmd.Equals(aPrevious.GetName()))
                {
                    SetPosition(-1);
                    if (NeedSave(newRow))
                    {
                        return;
                    }

                    /*cmd_save(false);*/
                    //m_curGC.getTable().removeEditor();
                    //m_curTab.navigateRelative(-1);
                    //m_curGC.requestFocusInWindow();
                }
                else if (cmd.Equals(aNext.GetName()))
                {	/*cmd_save(false); */
                    SetPosition(1);
                    if (NeedSave(newRow))
                    {
                        return;
                    }
                    //m_curGC.getTable().removeEditor();
                    //m_curTab.navigateRelative(+1);
                    //m_curGC.requestFocusInWindow();
                }
                else if (cmd.Equals(aLast.GetName()))
                {	/*cmd_save(false);*/
                    SetPosition(_curTab.GetRowCount() - 1);
                    if (NeedSave(newRow))
                    {
                        return;
                    }
                    //m_curGC.getTable().removeEditor();
                    //m_curTab.navigate(m_curTab.getRowCount()-1);
                    //m_curGC.requestFocusInWindow();
                }


                else if (cmd.Equals(aPageUp.GetName()) || cmd.Equals(aPageDown.GetName()))
                {	/*cmd_save(false); */
                    NavigatePage(cmd.Equals(aPageUp.GetName()), false);
                    //if (NeedSave(newRow))
                    //{
                    return;
                    //}
                    //m_curGC.getTable().removeEditor();
                    //m_curTab.navigateRelative(+1);
                    //m_curGC.requestFocusInWindow();
                }
                else if (cmd.Equals(aPageFirst.GetName()) || cmd.Equals(aPageLast.GetName()))
                {	/*cmd_save(false); */
                    NavigatePage(cmd.Equals(aPageFirst.GetName()), true);
                    //if (NeedSave(newRow))
                    //{
                    return;
                    //}
                    //m_curGC.getTable().removeEditor();
                    //m_curTab.navigateRelative(+1);
                    //m_curGC.requestFocusInWindow();
                }
                else if (cmd.Equals(aReport.GetName()))
                {
                    //SetBusy(true, true);
                    Cmd_Report();
                    return;
                }

                 //	Tools
                else if (aWorkflow != null && cmd.Equals(aWorkflow.GetName()))
                {
                    SetBusy(false, false);
                    if (_curTab.GetRecord_ID() <= 0)
                    { }
                    else if (_curTab.GetTabNo() == 0 && _mWorkbench.GetMWindow(GetWindowIndex()).IsTransaction())
                        AEnv.StartWorkflowProcess(_curTab.GetAD_Table_ID(), _curTab.GetRecord_ID());
                    else
                        AEnv.StartWorkflowProcess(_curTab.GetAD_Table_ID(), _curTab.GetRecord_ID());
                    return;
                }

                else if (cmd.Equals(aPrint.GetName()))
                {
                    Cmd_Print();
                    return;
                }
                else if (cmd.Equals(aEmail.GetName()))
                {
                    Cmd_Email();
                    //return;
                }
                else if (cmd.Equals(aFaxEMail.GetName()))
                {
                    Cmd_FaxEMail();
                }
                //else if (cmd.Equals(aEnd.GetName()))
                //{
                // //   Exit(false);
                //}
                //else if (cmd.Equals(aExit.GetName()))
                //{
                // //   Exit(true);
                //}
                //	Edit
                else if (cmd.Equals(aNew.GetName()))
                {
                    Cmd_New(false);
                    return;
                }
                else if (cmd.Equals(aNewG.GetName()))
                {
                    Cmd_New(false, false);
                    return;
                }
                else if (cmd.Equals(aSave.GetName()))
                {
                    Cmd_Save(true);
                    return;
                }
                else if (cmd.Equals(aCopy.GetName()))
                {
                    Cmd_New(true);
                    return;
                }
                else if (cmd.Equals(aDelete.GetName()))
                {
                    Cmd_Delete();
                    return;
                }
                else if (cmd.Equals(aDeleteSelection.GetName()))
                {
                    Cmd_DeleteSelection();
                    return;
                }
                else if (cmd.Equals(aIgnore.GetName()))
                {
                    UndoChanges();
                }
                else if (cmd.Equals(aRefresh.GetName()))
                {
                    Cmd_Refresh();
                    return;
                }
                else if (cmd.Equals(aFind.GetName()))
                {
                    Cmd_Find();
                }
                else if (_isPersonalLock && cmd.Equals(aLock.GetName()))
                    Cmd_Lock();
                //	View
                else if (cmd.Equals(aAttachment.GetName()))
                {

                    Cmd_Attachment();
                }
                else if (cmd.Equals(aChat.GetName()))
                {
                    Cmd_Chat();
                }
                else if (cmd.Equals(aMulti.GetName()))
                {
                    if (_curTab.GetRecord_ID() == -1)
                    {
                        aEmail.SetEnabled(false);
                    }
                    else
                    {
                        aEmail.SetEnabled(true);
                    }
                    aSms.SetEnabled(true);
                    _curGC.SwitchRowPresentation();
                    aDeleteSelection.SetEnabled(!_curGC.IsSingleRow() && !NeedSave(true));
                }

                else if (cmd.Equals(aLetter.GetName()))
                {
                    aLetter.SetEnabled(true);
                    Cmd_Letter();
                }
                else if (cmd.Equals(aSms.GetName()))
                {
                    Cmd_Sms();

                }
                else if (cmd.Equals(aAppointment.GetName()))
                {
                    Cmd_Appointment();
                }

                else if (cmd.Equals(aTask.GetName()))
                {
                    Cmd_Task();
                }

                else if (cmd.Equals(aEmailAttach.GetName()))
                {
                    int UID = Utility.Util.GetValueOfInt(Utility.Envs.GetContext().Get("#@UID"));
                    string userName = Envs.GetContext().Get("#@MailUser");
                    string folderName = Envs.GetContext().Get("#@FolderName");
                    int windowID = _curTab.GetAD_Window_ID();
                    if (UID == 0 || userName == null || folderName == null)
                    {
                        ShowMessage.Info("NoAttachementFound", true, "", "");
                    }
                    else
                    {

                        int recordID = _curTab.GetRecord_ID();
                        int tableID = _curTab.GetAD_Table_ID();
                        string tableName = _curTab.GetTableName();
                        var newclient = AEnv.GetNewMailServiceClient();
                        //Services.MailService.Execute((client) =>
                        //    {
                        //client.ClipBoardCompleted += (s, ev) =>
                        //{
                        newclient.ClipBoardCompleted += (ss, ee) =>
                        {
                            try
                            {

                                string[] response = ee.Result.Split(';');
                                if (response[2] == "")
                                {
                                    ShowMessage.Info("Success", true, "Window:" + response[0] + '\t' + "Record_ID:" + response[1], "");
                                }
                                else
                                {
                                    ShowMessage.Info(response[2], true, "Window:" + response[0] + '\t' + "Record_ID:" + response[1], "");
                                }
                            }
                            catch
                            {
                                ShowMessage.Info("Failed", true, "", "");
                            }
                            newclient.CloseAsync();
                        };
                        newclient.ClipBoardAsync((Dictionary<string, string>)_ctx.GetMap(), recordID, tableID, windowID);


                        newclient.CloseAsync();
                        // };
                        //client.ClipBoardAsync((Dictionary<string, string>)_ctx.GetMap(), recordID, tableID, windowID);
                        //});
                    }

                }

                //else if (cmd.Equals(aParent.GetName()))
                //    Cmd_Parent();
                //else if (cmd.Equals(aDetail.GetName()))
                //    Cmd_Detail();
                else if (cmd.Equals(aZoomAcross.GetName()))
                {
                    Cmd_ZoomAcross();
                    return;
                }
                else if (cmd.Equals(aRequest.GetName()))
                {
                    Cmd_Request();
                    return;
                }
                else if (cmd.Equals(aHelp.GetName()))
                    Cmd_Help();
                else if (cmd.Equals(aRoleCenterView.GetName()))
                {
                    Cmd_Find(true);
                }
                else if (cmd.Equals(aArchive.GetName()))
                    Cmd_Archive();
                else if (cmd.Equals(aImportMap.GetName()))
                    Cmd_ImportMap();
                else if (cmd.Equals(aMarkToExport.GetName()))
                    Cmd_MarkToExport();
                //else if (cmd.Equals("Home"))
                //{
                //    SetBusy(false, false);
                //    ContainerControl frm = Utility.Env.GetWindow(1);
                //    if (frm is Form)
                //    {
                //        ((Form)frm).Activate();
                //        frm.BringToFront();
                //    }
                //    frm = null;
                //    return;
                //}
                else if (cmd.Equals(aSubscribe.GetName()))
                {
                    cmd_Subscribed();
                    return;
                    //Subscribe subscribe = new Subscribe();
                    //subscribe.Insert(_curTab.GetAD_Window_ID(), _curTab.GetRecord_ID(), _curTab.GetAD_Table_ID());
                    //System.Threading.ThreadPool.QueueUserWorkItem(delegate
                    //{
                    //    if (_curTab.GetRecord_ID() != -1)
                    //    {
                    //        Subscribe Subscribe = new Subscribe();
                    //        bool isSubscribed = Subscribe.CheckSubscription(_curTab.GetAD_Window_ID(), _curTab.GetRecord_ID(), _curTab.GetAD_Table_ID()) == 0 ? false : true;
                    //        Dispatcher.BeginInvoke(delegate
                    //        {
                    //            aSubscribe.SetPressed(isSubscribed);
                    //        });
                    //    }
                    //});
                }
                else if (!AEnv.ActionPerformed(cmd, _curWindowNo, this))
                    log.Log(Level.SEVERE, "No action for: " + cmd);

            }
            catch (Exception ex)
            {
                //   log.Log(Level.SEVERE, cmd, ex);
                String msg = ex.Message;
                //if (msg == null || msg.Length == 0)
                //	msg = ex.ToString();
                msg = Msg.ParseTranslation(_ctx, msg);
                //MessageBox.Show("error <==>" + msg);
                ShowMessage.Error("Error?", true, "error <==>" + msg);
                //ADialog.error(m_curWindowNo, this, "Error", msg);
            }
            //
            //_curWinTab.Focus();
            //_curGC.RequestFocusInWindow();
            _curWinTab.Focus();
            SetBusy(false, true);
        }

        private void NavigatePage(bool isUp, bool isPageFirstLast)
        {
            SetBusy(true, false);

            if (isPageFirstLast)
            {
                if (isUp)
                {
                    _curTab.GetTableObj().SetCurrentPage(1);
                }
                else
                {
                    _curTab.GetTableObj().SetCurrentPage(_totalPage);
                }
            }

            else
            {
                if (isUp)
                {
                    _curTab.GetTableObj().SetCurrentPage(--_curPage);
                }
                else
                {
                    _curTab.GetTableObj().SetCurrentPage(++_curPage);
                }
            }

            MRole role = MRole.GetDefault();
            _curGC.query(_curTab.GetOnlyCurrentDays(),
                 role.GetMaxQueryRecords(), false);	//	updated
        }

        #endregion

        #region Command Action


        private void Cmd_Appointment()
        {
            int record_ID = _curTab.GetRecord_ID();
            ///Check table has Email column

            int AD_Table_ID = _curTab.GetAD_Table_ID();
            log.Info("Record_ID=" + record_ID);
            if (record_ID == -1)	//	No Key
            {
                return;
            }
            VAdvantage.Scheduler.AppointmentForm frm = new Scheduler.AppointmentForm(AD_Table_ID, record_ID, false);
            frm.Show();
        }

        private void Cmd_Task()
        {
            int record_ID = _curTab.GetRecord_ID();
            ///Check table has Email column

            int AD_Table_ID = _curTab.GetAD_Table_ID();
            log.Info("Record_ID=" + record_ID);
            if (record_ID == -1)	//	No Key
            {
                return;
            }
            VAdvantage.Scheduler.AppointmentForm frm = new Scheduler.AppointmentForm(AD_Table_ID, record_ID, true);
            // VAdvantage.Scheduler.AppointmentForm frm = new Scheduler.AppointmentForm(true);
            frm.Show();
        }

        private MethodInfo mehtodinfo = null;
        private List<object> arguments = new List<object>();


        private void Cmd_New(bool copy)
        {
            Cmd_New(copy, true);
        }
        private void Cmd_New(bool copy, bool toogle)
        {

            if (!_curTab.CheckDataNew())
            {
                SetBusy(false, false);
                return;
            }

            blockEvent = true;
            newRow = true;
            //this.Cursor = Cursors.Wait;
            _curGC.AddNewRow(copy, toogle);
            //  AddNewRow(copy);
            //Get Default value
            //if (NeedSave(false))
            //{
            //    mehtodinfo = this.GetType().GetMethod("Cmd_NewAfterSave");
            //    arguments.Add(copy);
            //    SaveData(true);
            //    return;
            //}
            //Cmd_NewAfterSave(copy);
            //_curGC.ReDrawCurrentRow();
        }

        //private void Cmd_NewAfterSave(bool copy)
        //{
        //    if (!_curTab.CheckDataNew())
        //    {
        //        SetBusy(false, false);
        //        return;
        //    }
        //    AddNewRow(copy);

        //}

        private bool Cmd_Save(bool manual)
        {
            return SaveData(manual);
        }

        private void Cmd_Delete()
        {
            //isCurentRowDirty = false;
            if (_curTab.IsReadOnly())
            {
                SetBusy(false, true);
                return;
            }
            int keyID = _curTab.GetRecord_ID();// GetRecordID();

            //MessageBoxResult dd = MessageBox.Show(Msg.GetMsg(_ctx, "DeleteRecord?"),"Delete",MessageBoxButton.OKCancel);

            ShowMessage.AskMessage("DeleteRecord?", true, "").Closed += (s, e) =>
                {
                    if (true.Equals(((Message)s).DialogResult))
                    {
                        blockEvent = true;
                        _curGC.DeleteDataRow();
                        blockEvent = false;
                    }
                    else
                    {
                        SetBusy(false, true);
                        return;
                    }
                };
        }


        /// <summary>
        /// Show a list to select one or more items to delete.
        /// </summary>
        private void Cmd_DeleteSelectionOriginal()
        {
            if (_curTab.IsReadOnly())
            {
                SetBusy(false);
                return;
            }

            ListBox list = new ListBox();
            //list.Dock = DockStyle.Fill;
            //list.Margin = new Padding(4);
            list.SelectionMode = SelectionMode.Extended;

            List<String> data = new List<String>();

            String keyColumnName = _curTab.GetKeyColumnName();
            String sql = null;
            if (!"".Equals(keyColumnName))
            {
                sql = MLookupFactoryCache.GetLookup_TableDirEmbed(Envs.GetLanguage(_ctx), keyColumnName, "[?", "?]", "SL")
                   .Replace("[?.?]", "@param0");
            }
            int noOfRows = _curGC.RowCount();

            List<string> sqlList = null;

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                if (!"".Equals(keyColumnName)) //If not found in cache local storage(preventive case)
                {
                    if (sql == null || sql.Length < 1)
                    {
                        sql = MLookupFactory.GetLookup_TableDirEmbed(Envs.GetLanguage(_ctx), keyColumnName, "[?", "?]")
                       .Replace("[?.?]", "@param0");
                    }
                }

                for (int i = 0; i < noOfRows; i++)
                {
                    StringBuilder displayValue = new StringBuilder();
                    if ("".Equals(keyColumnName))
                    {
                        List<String> parentColumnNames = _curTab.GetParentColumnNames();
                        foreach (String iter in parentColumnNames)
                        {
                            String columnName = iter;
                            GridField field = _curTab.GetField(columnName);
                            if (field.IsLookup())
                            {
                                Lookup lookup = field.GetLookup();
                                if (lookup != null)
                                {
                                    displayValue = displayValue.Append(lookup.GetDisplay(_curTab.GetValue(i, columnName))).Append(" | ");
                                }
                                else
                                {
                                    displayValue = displayValue.Append(_curTab.GetValue(i, columnName)).Append(" | ");
                                }
                            }
                            else
                            {
                                displayValue = displayValue.Append(_curTab.GetValue(i, columnName)).Append(" | ");
                            }
                        }
                        data.Add(displayValue.ToString());
                    }
                    else
                    {
                        int id = _curGC.GetKeyID(i, keyColumnName);

                        string sql1 = sql.Replace("@param0", id.ToString());

                        if (sqlList == null)
                        {
                            sqlList = new List<string>();
                        }
                        sqlList.Add(sql1);

                        //String value = DB.GetSQLValueStringEx(null, sql, new object[] { id });
                        //if (value != null)
                        //    value = value.Replace(" - ", " | ");
                        //displayValue.Append(value);
                        //// Append ID
                        //if (displayValue.Length == 0 || VLogMgt.IsLevelFine())
                        //{
                        //    if (displayValue.Length > 0)
                        //        displayValue.Append(" | ");
                        //    displayValue.Append("<").Append(id).Append(">");
                        //}
                    }
                }

                if (sqlList != null && sqlList.Count > 0)
                {
                    object[] value = null;
                    try
                    {
                        value = DB.GetSQLScalarValueObjectEx(null, sqlList.ToArray());
                    }
                    catch (Exception e)
                    {
                        log.Severe(e.Message);
                        Dispatcher.BeginInvoke(() => SetBusy(false));
                        return;
                    }

                    foreach (object o in value)
                    {
                        data.Add(o.ToString());
                    }
                }

                Dispatcher.BeginInvoke(delegate
                {
                    list.ItemsSource = data;

                    FormTemplate tmp = new FormTemplate();
                    tmp.LayoutRoot.Children.Add(list);
                    tmp.Closed += (frm, ev) =>
                        {
                            if (tmp.DialogResult != null && (bool)tmp.DialogResult)
                            {
                                log.Fine("ok");

                                selectedItemIndexes = new List<int>();
                                foreach (object o in list.SelectedItems)
                                    selectedItemIndexes.Add(list.Items.IndexOf(o));

                                IList selectedValues = list.SelectedItems;
                                for (int i = 0; i < selectedValues.Count; i++)
                                {
                                    log.Fine(selectedValues[i].ToString());
                                }

                                if (selectedItemIndexes.Count < 1)
                                {
                                    selectedValues = null;
                                    selectedItemIndexes = null;
                                    return;
                                }

                                SetBusy(true, false);
                                offset = 0;
                                _curGC.DeleteCompleted += new EventHandler(_curGC_DeleteCompleted);


                                //for (int i = 0; i < selectedValues.Count; i++)
                                //{
                                _curGC.SetCurrentRowIndex(0);
                                _curGC.SetPostion(selectedItemIndexes[0] - offset);
                                //        _curGC.GetDataSource().Position = list.SelectedIndices[i] - offset;
                                //int keyID = _curTab.GetRecord_ID();
                                selectedItemIndexes.RemoveAt(0);
                                _curGC.DeleteDataRow();
                                //        {
                                //            offset++;
                                //        }
                                //    }
                                //  _curGC.DynamicDisplay("");
                                //    SetBusy(false, false);
                                //}
                                //else
                                //{
                                //    log.Fine("cancel");
                                //}
                            }

                        };
                    tmp.Show();
                    SetBusy(false);

                });

            });


        }

        private void Cmd_DeleteSelection()
        {
            if (_curTab.IsReadOnly())
            {
                SetBusy(false);
                return;
            }

            int noOfRows = _curGC.RowCount();

            List<string> sqlList = null;
            //List<DataGridRow> rows = new List<DataGridRow>(_curGC.GetSelectedDataGridRow());

            IList rows = _curGC.GetSelectedRows();

            if (rows.Count > 0)
            {

                ShowMessage.AskMessage("DeleteRecord?", true, " ==> {" + rows.Count.ToString() + " }").Closed += (frm, ev) =>
                    {
                        if (((Message)frm).DialogResult.Value)
                        {

                            selectedItemIndexes = new List<int>();
                            foreach (object o in rows)
                            {
                                selectedItemIndexes.Add(_curGC.GetBindingSource().IndexOf(o));
                                //selectedItemIndexes.Add(o.GetIndex());
                            }

                            // IList selectedValues = rows;
                            //for (int i = 0; i < selectedValues.Count; i++)
                            //{
                            //    log.Fine(selectedValues[i].ToString());
                            //}

                            if (selectedItemIndexes.Count < 1)
                            {
                                // selectedValues = null;
                                selectedItemIndexes = null;
                                return;
                            }

                            SetBusy(true, false);
                            offset = 0;
                            _curGC.DeleteCompleted += new EventHandler(_curGC_DeleteCompleted);


                            //for (int i = 0; i < selectedValues.Count; i++)
                            //{
                            _curGC.SetCurrentRowIndex(0);
                            _curGC.SetPostion(selectedItemIndexes[0] - offset);
                            //        _curGC.GetDataSource().Position = list.SelectedIndices[i] - offset;
                            //int keyID = _curTab.GetRecord_ID();
                            selectedItemIndexes.RemoveAt(0);
                            _curGC.DeleteDataRow();
                        }

                        else
                        {
                            SetBusy(false);
                        }

                    };
            }
            else
            {
                SetBusy(false);
            }
        }

        List<int> selectedItemIndexes = null;
        int offset = 0;
        void _curGC_DeleteCompleted(object sender, EventArgs e)
        {
            bool isDeleted = ((DeleteEventArgs)e).IsDeleted;


            offset++;
            if (!isDeleted || selectedItemIndexes.Count < 1)
            {
                offset = 0;
                selectedItemIndexes = null;
                _curGC.DeleteCompleted -= _curGC_DeleteCompleted;
                _curGC.DynamicDisplay("");
                _curGC.RefreshGrid();
                SetBusy(false);
                return;
            }
            _curGC.SetCurrentRowIndex(0);
            _curGC.SetPostion(selectedItemIndexes[0] - offset);
            //        _curGC.GetDataSource().Position = list.SelectedIndices[i] - offset;
            //int keyID = _curTab.GetRecord_ID();
            selectedItemIndexes.RemoveAt(0);
            _curGC.DeleteDataRow();

        }

        private void Cmd_Email()
        {

            int record_ID = _curTab.GetRecord_ID();
            List<DataGridRow> Rows = new List<DataGridRow>();
            IList rowsource = _curGC.GetSelectedRows();
            log.Info("Record_ID=" + record_ID);
            if (record_ID == -1)	//	No Key
            {
                return;
            }

            string to = "";
            if (((DataUtil.DataObject)rowsource[0]).GetFieldValue("EMAIL") != null)
            {
                if (_curGC.IsSingleRow())
                {
                    object a = _curTab.GetValue("Email");
                    if (a != null)
                    {
                        to = a.ToString();
                    }
                }

                else//multi row selected
                {
                    //_curGC.ge
                    int count = rowsource.Count;
                    if (count == 1)
                    {
                        object a = _curTab.GetValue("Email");
                        if (a != null)
                        {
                            to = a.ToString();
                        }
                    }
                    else
                    {
                        for (int i = 0; i < rowsource.Count; i++)
                        {
                            if (((DataUtil.DataObject)rowsource[i]).GetFieldValue("EMAIL") != null)
                            {
                                to += ((DataUtil.DataObject)rowsource[i]).GetFieldValue("EMAIL").ToString().Trim() + ",";
                            }
                        }
                        while (to.EndsWith(","))
                        {
                            to = to.Substring(0, to.Length - 1);
                        }
                    }
                }
            }
            else
            {

            }
            VAdvantage.Framework.Email emailText = new Email(_ctx, Msg.GetMsg(_ctx, "EMail"), to, _curTab, record_ID, true, _curGC);
            Utility.Envs.RegisterWindowForm(emailText);
            Envs.ShowForm(emailText);
        }


        private void Cmd_FaxEMail()
        {
            int record_ID = _curTab.GetRecord_ID();
            List<DataGridRow> Rows = new List<DataGridRow>();
            IList rowsource = _curGC.GetSelectedRows();
            log.Info("Record_ID=" + record_ID);
            if (record_ID == -1)	//	No Key
            {
                return;
            }

            string to = "";
            if (((DataUtil.DataObject)rowsource[0]).GetFieldValue("FaxEmail") != null)
            {
                if (_curGC.IsSingleRow())
                {
                    object a = _curTab.GetValue("FaxEmail");
                    if (a != null)
                    {
                        to = a.ToString();
                    }
                }

                else//multi row selected
                {
                    //_curGC.ge
                    int count = rowsource.Count;
                    if (count == 1)
                    {
                        object a = _curTab.GetValue("FaxEmail");
                        if (a != null)
                        {
                            to = a.ToString();
                        }
                    }
                    else
                    {
                        for (int i = 0; i < rowsource.Count; i++)
                        {
                            if (((DataUtil.DataObject)rowsource[i]).GetFieldValue("FaxEmail") != null)
                            {
                                to += ((DataUtil.DataObject)rowsource[i]).GetFieldValue("FaxEmail").ToString().Trim() + ",";
                            }
                        }
                        while (to.EndsWith(","))
                        {
                            to = to.Substring(0, to.Length - 1);
                        }
                    }
                }
            }
            else
            {

            }
            VAdvantage.Framework.Email emailText = new Email(_ctx, Msg.GetMsg(_ctx, "FaxEmail"), to, _curTab, record_ID, _curGC);
            Utility.Envs.RegisterWindowForm(emailText);
            Envs.ShowForm(emailText);
        }

        private void Cmd_Letter()
        {
            int record_ID = _curTab.GetRecord_ID();
            List<DataGridRow> Rows = new List<DataGridRow>();
            IList rowsource = _curGC.GetSelectedRows();
            log.Info("Record_ID=" + record_ID);
            if (record_ID == -1)	//	No Key
            {
                //  aLetter.SetEnabled(false);
                return;

            }

            string to = "";
            if (_curGC.IsSingleRow())
            {
                object a = _curTab.GetValue("C_Location_ID");
                if (a != null)
                {
                    to = a.ToString();
                }
            }

            else//multi row selected
            {
                //_curGC.ge
                int count = _curGC.GetSelectedRows().Count;
                if (count == 1)
                {
                    object a = _curTab.GetValue("C_Location_ID");
                    if (a != null)
                    {
                        to = a.ToString();
                    }
                }

            }
            //    VAdvantage.Framework.Email letter = new Email(_ctx, Msg.GetMsg(_ctx, "Letter"), _curGC.GetSelectedRows(), _curGC.GetMTab().GetAD_Table_ID(), to, _curTab, record_ID, false, _curGC);
            VAdvantage.Framework.Email letter = new Email(_ctx, Msg.GetMsg(_ctx, "Letter"), to, _curTab, record_ID, false, _curGC);
            Utility.Envs.RegisterWindowForm(letter);
            Envs.ShowForm(letter);
        }


        /// <summary>
        /// Undo Changes 
        /// </summary>
        /// <param name="isNewRow"></param>
        public void UndoChanges()
        {
            blockEvent = true;
            //SetBusy(true,true);
            //_curGC.Select();
            _curGC.UndoChanges(newRow);
            //_curTab.GetTableObj().DataIgnore();
            //}
            SetRowState(false, false);
            SetButtons(false, true);
            SetNavigateButtons();
            SetToolStripButtons();
            //if (!_curGC.IsSingleRow())
            //{
            //    _curGC.ReDrawCurrentRow();
            //}
            //blockEvent = false;
            // _curTab.CurrentRow = this.BindingSource.Position;
            blockEvent = false;
            //SetBusy(false,true);
        }

        private void Cmd_Refresh()
        {
            if (NeedSave(true))
            {
                mehtodinfo = this.GetType().GetMethod("Cmd_RefreshAfterSave");
                SaveData(false);
                return;
            }
            Cmd_RefreshAfterSave();
        }

        private void Cmd_RefreshAfterSave()
        {
            blockEvent = true;
            try
            {
                _curGC.DataRefreshAll();
                //SetNavigateButtons();
            }
            catch (Exception e)
            {
                //log.Log(Level.WARNING, e.Message);
            }
            blockEvent = false;

        }

        /* Query */
        private Query _reportQuery;
        Find find = new Find();
        /// <summary>
        /// Search
        /// </summary>
        /// 
        Action method;
        private void Cmd_Find(bool frameOpen)
        {
            if (_curTab == null)
                return;
            //if (NeedSave(false))
            //{
            //    SaveData(false);
            //    return;
            //}
            Cmd_FindAfterSave(frameOpen);

        }
        private void Cmd_Find()
        {
            Cmd_Find(false);
        }

        private void Cmd_ImportMap()
        {
            blockEvent = true;
            int record_ID = _curTab.GetAD_Window_ID();
            VAdvantage.ImpExp.ExcelImport cox = new ImpExp.ExcelImport(record_ID, _mWorkbench.GetMWindow(GetWindowIndex()).GetName());
            //cox.Show();
            Envs.ShowForm(cox);
            blockEvent = false;
        }

        private void Cmd_MarkToExport()
        {


            int record_ID = _curTab.GetRecord_ID();
            List<DataGridRow> Rows = new List<DataGridRow>();
            IList rowsource = _curGC.GetSelectedRows();
            log.Info("Record_ID=" + record_ID);
            if (record_ID == -1)	//	No Key
            {

                int table_ID = _curTab.GetAD_Table_ID();
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    string[] keyNames = new MTable(Envs.GetCtx(), table_ID, null).GetKeyColumns();
                    Dispatcher.BeginInvoke(delegate
                    {
                        //List<string> keyNames =_curTab.GetParentColumnNames();
                        string _recordID = "";
                        string _recordID2 = "";

                        if (_curGC.IsSingleRow())
                        {
                            object a = _curTab.GetValue(keyNames[0]);
                            object b = _curTab.GetValue(keyNames[1]);
                            if (a != null && b != null)
                            {
                                _recordID = a.ToString();
                                _recordID2 = b.ToString();
                            }
                        }
                        else
                        {
                            int count = rowsource.Count;
                            if (count == 1)
                            {
                                object a = _curTab.GetValue(keyNames[0]);
                                object b = _curTab.GetValue(keyNames[1]);
                                if (a != null && b != null)
                                {
                                    _recordID = a.ToString();
                                    _recordID2 = b.ToString();
                                }
                            }
                            else
                            {
                                for (int i = 0; i < rowsource.Count; i++)
                                {
                                    if (((DataUtil.DataObject)rowsource[i]).GetFieldValue(keyNames[0].ToUpper()) != null && ((DataUtil.DataObject)rowsource[i]).GetFieldValue(keyNames[1].ToUpper()) != null)
                                    {
                                        _recordID += ((DataUtil.DataObject)rowsource[i]).GetFieldValue(keyNames[0].ToUpper()).ToString().Trim() + ",";
                                        _recordID2 += ((DataUtil.DataObject)rowsource[i]).GetFieldValue(keyNames[1].ToUpper()).ToString().Trim() + ",";
                                    }
                                }
                                while (_recordID.EndsWith(",") || _recordID2.EndsWith(","))
                                {
                                    _recordID = _recordID.Substring(0, _recordID.Length - 1);
                                    _recordID2 = _recordID2.Substring(0, _recordID2.Length - 1);
                                }
                            }
                        }
                        aMarkToExport.SetPressed(_curTab.HasExportRecord());
                        MarkModule objMM = new MarkModule(_recordID, _recordID2, _curTab.GetTableObj().GetTableID(), _curTab.GetTableName());
                        objMM.Show();
                        System.Threading.ThreadPool.QueueUserWorkItem(delegate
                        {
                            while (!objMM.isSaved)
                            {
                            }
                            _curTab.LoadExport();
                            //while (_curTab.isExportLoading)
                            //{
                            //}

                            _curTab.isExportLoading = false;
                            Dispatcher.BeginInvoke(delegate
                            {
                                aMarkToExport.SetPressed(_curTab.HasExportRecord());
                            });
                        });
                    });
                });

            }
            else
            {
                string _primaryKey = _curTab.GetTableName().ToString() + "_ID";
                string _recordID = "";

                //if (((DataUtil.DataObject)rowsource[0]).GetFieldValue("EMAIL") != null)
                //{
                if (_curGC.IsSingleRow())
                {
                    object a = _curTab.GetValue(_primaryKey.ToUpper());
                    if (a != null)
                    {
                        _recordID = a.ToString();
                    }
                }

                else//multi row selected
                {
                    //_curGC.ge
                    int count = rowsource.Count;
                    if (count == 1)
                    {
                        object a = _curTab.GetValue(_primaryKey.ToUpper());
                        if (a != null)
                        {
                            _recordID = a.ToString();
                        }
                    }
                    else
                    {
                        for (int i = 0; i < rowsource.Count; i++)
                        {
                            if (((DataUtil.DataObject)rowsource[i]).GetFieldValue(_primaryKey.ToUpper()) != null)
                            {
                                _recordID += ((DataUtil.DataObject)rowsource[i]).GetFieldValue(_primaryKey.ToUpper()).ToString().Trim() + ",";
                            }
                        }
                        while (_recordID.EndsWith(","))
                        {
                            _recordID = _recordID.Substring(0, _recordID.Length - 1);
                        }
                    }
                }

                aMarkToExport.SetPressed(_curTab.HasExportRecord());
                MarkModule objMM = new MarkModule(_recordID, _curTab.GetTableObj().GetTableID(), _curTab.GetTableName());
                objMM.Show();
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    while (!objMM.isSaved)
                    {
                    }
                    _curTab.LoadExport();
                    _curTab.isExportLoading = false;
                    Dispatcher.BeginInvoke(delegate
                    {
                        aMarkToExport.SetPressed(_curTab.HasExportRecord());
                    });
                });
            }

        }


        private void Cmd_FindAfterSave(bool frameOpen)
        {
            GridField[] findFields = _curTab.GetFields();
            //find = new Find(_curWindowNo, _curTab.GetName(), _curTab.GetAD_Tab_ID(),
            //_curTab.GetAD_Table_ID(), _curTab.GetTableName(),
            //_curTab.GetWhereClause(), findFields, 0);

            find = new Find(_curWindowNo, _curTab, findFields, 0, frameOpen);

            find.Show();
            bool result = Util.GetValueOfBool(find.DialogResult);
            find.Closing += new EventHandler<System.ComponentModel.CancelEventArgs>(find_Closing);
        }

        void find_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (find != null)
            {
                // fetches filtered data only when OK button is clicked
                if (find.GetIsOKPressed())
                {
                    //	Simple/Advanced Query
                    Query query = find.GetQuery();
                    _reportQuery = query;   //added by jagmohan bhatt for filtered report
                    //	History
                    int onlyCurrentDays = find.GetCurrentDays();
                    bool created = find.GetIsCreated();

                    find = null;

                    //Stop callout
                    blockEvent = true;
                    //	Confirmed query
                    //Set Page value to 1
                    _curTab.GetTableObj().SetCurrentPage(1);
                    if (query != null && query.IsActive())
                    {
                        //log.config(query.toString());
                        _curTab.SetQuery(query);
                        _curGC.query(0, 0, created);   //  autoSize
                    }
                    else
                    {
                        int maxRows = MRole.GetDefault().GetMaxQueryRecords();
                        //log.config("OnlyCurrentDays=" + onlyCurrentDays + ", MaxRows=" + maxRows);
                        _curTab.SetQuery(null);	//	reset previous queries
                        _curGC.query(onlyCurrentDays, maxRows, created);   //  autoSize
                    }

                    // _curGC.SetCurrentRowData();
                    bool findPressed = _curTab.IsQueryActive() || _curTab.GetOnlyCurrentDays() > 0;
                    aFind.SetPressed(findPressed);
                    _curGC.DynamicDisplay("");
                    SetNavigateButtons();
                    SetToolStripButtons();
                    SetRowState(false, false);

                    cmbSearch.SelectedIndex = -1; //clear selection of window combo search

                    blockEvent = false;
                }
            }
        }

        private void Cmd_Lock()
        {
            //log.Info("Modifiers=" + _lastModifiers);
            bool locked = false;
            if (!_isPersonalLock)
            {
                return;
            }
            int record_ID = _curTab.GetRecord_ID();
            if (record_ID == -1)	//	No Key
            {
                return;
            }
            //	Control Pressed
            if ((_lastModifiers & (int)(Keyboard.Modifiers)) != 0)
            {
                RecordAccessDialog recordLock = new RecordAccessDialog(_curTab.GetAD_Table_ID(), record_ID);
                recordLock.Closing += (sc, ec) =>
                {
                    //locked = Util.GetValueOfBool(((RecordAccessDialog)sc).DialogResult);
                    System.Threading.ThreadPool.QueueUserWorkItem(delegate
                    {
                        locked = _curTab.IsLocked();
                        Deployment.Current.Dispatcher.BeginInvoke(() => aLock.SetPressed(locked));
                    });
                };
            }
            else
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                    {
                        //Raghu
                        _curTab.Locks(Envs.GetCtx(), record_ID, aLock.IsPressed());
                        _curTab.LoadAttachments();			//	reload
                        locked = _curTab.IsLocked();
                        Deployment.Current.Dispatcher.BeginInvoke(() => aLock.SetPressed(locked));
                    });
            }
        }

        /// <summary>
        /// Attachment
        /// </summary>
        private void Cmd_Attachment()
        {
            int record_ID = _curTab.GetRecord_ID();
            log.Info("Record_ID=" + record_ID);
            if (record_ID == -1)	//	No Key
            {
                aAttachment.SetEnabled(false);
                return;
            }

            AttachmentForm attachObj = new AttachmentForm(_curWindowNo, _curTab.GetAD_AttachmentID(),
                       _curTab.GetAD_Table_ID(), record_ID, null);
            attachObj.Show();
            attachObj.Closing += new EventHandler<CancelEventArgs>(attachObj_Closing);
            attachObj = null;
        }

        void attachObj_Closing(object sender, CancelEventArgs e)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                _curTab.LoadAttachments();
                Deployment.Current.Dispatcher.BeginInvoke(() => aAttachment.SetPressed(_curTab.HasAttachment()));
            });
        }

        /// <summary>
        ///chat 
        /// </summary>
        private void Cmd_Chat()
        {
            int record_ID = _curTab.GetRecord_ID();
            log.Info("Record_ID=" + record_ID);
            if (record_ID == -1)	//	No Key
            {
                aChat.SetEnabled(false);
                return;
            }
            //	Find display
            String infoName = null;
            String infoDisplay = null;
            for (int i = 0; i < _curTab.GetFieldCount(); i++)
            {
                GridField field = _curTab.GetField(i);
                if (field.IsKey())
                    infoName = field.GetHeader();
                if ((field.GetColumnName().Equals("Name") || field.GetColumnName().Equals("DocumentNo"))
                    && (field.GetValue() != null && field.GetValue() != DBNull.Value))                     //Changed BY lakhwinder   //chaged || to &&//
                    infoDisplay = field.GetValue().ToString();                                             //chat was not working lead window
                if (infoName != null && infoDisplay != null)
                    break;
            }
            String description = infoName + ": " + infoDisplay;

            Chat chatWinObj = new Chat(_curWindowNo, _curTab.GetCM_ChatID(), _curTab.GetAD_Table_ID(),
                record_ID, description, null);
            chatWinObj.Show();
            chatWinObj.Closing += new EventHandler<CancelEventArgs>(chatWinObj_Closing);

        }


        private void cmd_Subscribed()
        {
            int record_ID = _curTab.GetRecord_ID();
            log.Info("Record_ID=" + record_ID);
            if (record_ID == -1)	//	No Key
            {
                aSubscribe.SetEnabled(false);
                return;
            }
            bool flag = false;
            Subscribe Subscribe = new Subscribe();
            SetBusy(true, false);
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                if (_curTab.GetCM_SubScribedID() == 0)
                {
                    Subscribe.InsertSubscription(_curTab.GetAD_Window_ID(), record_ID, _curTab.GetAD_Table_ID());
                    flag = true;
                }
                else
                {
                    Subscribe.DeleteSubscription(_curTab.GetCM_SubScribedID());
                    flag = true;
                }
                while (!flag)
                {
                    System.Threading.Thread.Sleep(1);
                }
                _curTab.LoadSubscribe();
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    aSubscribe.SetPressed(_curTab.HasSubscribed());
                    SetBusy(false, false);
                });
            });


        }

        void chatWinObj_Closing(object sender, CancelEventArgs e)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                _curTab.LoadChats();				//	reload
                Deployment.Current.Dispatcher.BeginInvoke(() => aChat.SetPressed(_curTab.HasChat()));
            });

        }

        /// <summary>
        ///Print specific Report - or start default Report
        /// </summary>
        private void Cmd_Print()
        {
            ProcessCtl pctrl = null;

            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (ov, ev) =>
            {
                //	Get process defined for this tab
                int AD_Process_ID = _curTab.GetAD_Process_ID();
                log.Info("ID=" + AD_Process_ID);

                //	No report defined
                if (AD_Process_ID == 0)
                {
                    Dispatcher.BeginInvoke(() => SetBusy(false, false));
                    //Cmd_Report();
                    return;
                }
                if (NeedSave(false))
                {
                    if (!Cmd_Save(true))
                    {
                        return;
                    }
                }

                //Cmd_Save(false);
                //
                int table_ID = _curTab.GetAD_Table_ID();
                int record_ID = _curTab.GetRecord_ID();
                ProcessInfo pi = new ProcessInfo(GetTitle(), AD_Process_ID, table_ID, record_ID);
                pi.SetAD_User_ID(_ctx.GetAD_User_ID());
                pi.SetAD_Client_ID(_ctx.GetAD_Client_ID());

                pctrl = new ProcessCtl(this, pi, null);
                pctrl.Process(_curWindowNo);
            };

            bgw.RunWorkerAsync();

        }

        public void Cmd_Report()
        {
            AReport report = null;
            Query rquery = null;
            SetBusy(true, true);
            ATreeViewItem item = aReport.GetTreeViewItem();
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (ov, ev) =>
            {
                log.Info("");
                if (!MRole.GetDefault().IsCanReport(_curTab.GetAD_Table_ID()))
                {
                    ShowMessage.Error("AccessCannotReport", true);
                    return;
                }
                if (NeedSave(false))
                {
                    Dispatcher.BeginInvoke(() => Cmd_Save(true));
                    //if (!Cmd_Save(true))
                    //{
                    //    return;
                    //}
                    return;
                }


                if (_reportQuery != null)
                    rquery = _reportQuery;
                else
                    rquery = new Query(_curTab.GetTableName());

                //	Link for detail records
                String queryColumn = _curTab.GetLinkColumnName();
                //	Current row otherwise
                if (queryColumn.Length == 0)
                    queryColumn = _curTab.GetKeyColumnName();
                //	Find display
                String infoName = null;
                String infoDisplay = null;
                for (int i = 0; i < _curTab.GetFieldCount(); i++)
                {
                    GridField field = _curTab.GetField(i);
                    if (field.IsKey())
                        infoName = field.GetHeader();
                    if ((field.GetColumnName().Equals("Name") || field.GetColumnName().Equals("DocumentNo"))
                        && field.GetValue() != null)
                        infoDisplay = field.GetValue().ToString();
                    if (infoName != null && infoDisplay != null)
                        break;
                }

                bool isParent = _curTab.GetParentColumnNames().Count.Equals(0);
                if (queryColumn.Length != 0)
                {
                    if (!isParent)    //only selected record to be printed
                    {
                        if (queryColumn.EndsWith("_ID"))
                            rquery.AddRestriction(queryColumn, Query.EQUAL,
                                _ctx.GetContextAsInt(_curWindowNo, queryColumn),
                                infoName, infoDisplay);
                        else
                            rquery.AddRestriction(queryColumn, Query.EQUAL,
                                _ctx.GetContext(_curWindowNo, queryColumn),
                                infoName, infoDisplay);
                    }
                }

                report = new VAdvantage.Print.AReport(_curTab.GetAD_Table_ID(), aReport.GetButton(), rquery, this);
            };

            bgw.RunWorkerCompleted += (ov, ev) =>
            {
                if (report != null)
                {
                    PdfViewer pdf = new PdfViewer(report.ReportPdfInfo.Report, _curTab.GetAD_Table_ID(), _curTab.GetTableName());
                    pdf.SetQuery = rquery;   //Set the query to pdfviewer
                    pdf.AD_PrintFormat_ID = report.ReportPdfInfo.AD_PrintFormat_ID;
                    Envs.RegisterWindowForm(pdf);
                    pdf.Show();

                }
                SetBusy(false);
            };

            bgw.RunWorkerAsync();

        }

        private void Cmd_Sms()
        {

            int record_ID = _curTab.GetRecord_ID();
            IList rowSource = _curGC.GetSelectedRows() as IList;

            ///Check table has Email column
            if (_curTab.GetField("Mobile") == null)
            {
                //aSms.SetEnabled(false);
                log.SaveError(Msg.GetMsg(Envs.GetCtx(), "MobileNotFound"), "");
                //SetStatusLine(Msg.GetMsg(Envs.GetCtx(), "MobileFieldNotFound"), true);
                //return;
                VAdvantage.Framework.Sms smsWin = new VAdvantage.Framework.Sms(_curTab, this, _curGC);
                Utility.Envs.RegisterWindowForm(smsWin);
                Envs.ShowForm(smsWin);
                return;

            }

            log.Info("Record_ID=" + record_ID);
            if (record_ID == -1)	//	No Key
            {
                //aSms.SetEnabled(false);
                //return;
                VAdvantage.Framework.Sms smsWin = new VAdvantage.Framework.Sms(_curTab, this, _curGC);
                Utility.Envs.RegisterWindowForm(smsWin);
                Envs.ShowForm(smsWin);
                return;
            }

            string to = "";
            if (_curGC.IsSingleRow())
            {
                object a = _curTab.GetValue("Mobile");
                if (a != null)
                {
                    to = a.ToString();
                }
            }
            else//multi row selected
            {
                //_curGC.ge
                int count = rowSource.Count;
                if (count == 1)
                {
                    object a = _curTab.GetValue("Mobile");
                    if (a != null)
                    {
                        to = a.ToString();
                    }
                }
                else
                {

                    // foreach (DataGridRow dr in _curGC.GetSelectedRowsCount())
                    for (int i = 0; i < rowSource.Count; i++)
                    {
                        // to += dr.Cells["Mobile"].Value.ToString().Trim() + ",";
                        //to += (BindableObject)rowSource[i]).GetValue["Mobile"].ToString().Trim() + ",";
                        if (((DataUtil.DataObject)rowSource[i]).GetFieldValue("MOBILE") != null)
                        {
                            to += ((DataUtil.DataObject)rowSource[i]).GetFieldValue("MOBILE").ToString().Trim() + ",";
                        }
                    }
                    while (to.EndsWith(","))
                    {
                        to = to.Substring(0, to.Length - 1);
                    }
                }
            }
            if (to != null && to.Length > 0)
            {
                //VAdvantage.Framework.Sms smsWin = new Sms(_ctx, Msg.GetMsg(_ctx, "Sms"), (DataGrid)_curGC.GetSelectedRows(), _curGC.GetMTab().GetAD_Table_ID(), to, _curTab, record_ID, false, _curGC);
                //VAdvantage.Framework.Sms smsWin = new Sms(_ctx, Msg.GetMsg(_ctx, "Sms"), _curGC.GetSelectedRows(), _curGC.GetMTab().GetAD_Table_ID(), to, _curTab, record_ID, false, _curGC);
                VAdvantage.Framework.Sms smsWin = new VAdvantage.Framework.Sms(_ctx, Msg.GetMsg(_ctx, "Sms"), to, _curTab, record_ID, false, _curGC, this);
                Utility.Envs.RegisterWindowForm(smsWin);
                Envs.ShowForm(smsWin);
            }
            else
            {
                //SetStatusLine(Msg.GetMsg(Envs.GetCtx(), "RecordNotFound"), true);
                VAdvantage.Framework.Sms smsWin = new VAdvantage.Framework.Sms(_curTab, this, _curGC);
                Utility.Envs.RegisterWindowForm(smsWin);
                Envs.ShowForm(smsWin);
            }

            //Activity act = new Activity();
            //Envs.RegisterWindowForm(act);
            //act.Show();


        }

        private void Cmd_ZoomAcross()
        {
            int Record_ID = _curTab.GetRecord_ID();
            log.Info("ID=" + Record_ID);
            if (Record_ID <= 0)
            {
                SetBusy(false);
                return;
            }

            //	Query
            Query query = new Query();
            //	Current row
            String link = _curTab.GetKeyColumnName();
            //	Link for detail records
            if (link.Length == 0)
                link = _curTab.GetLinkColumnName();
            if (link.Length != 0)
            {
                if (link.EndsWith("_ID"))
                    query.AddRestriction(link, Query.EQUAL, _ctx.GetContextAsInt(_curWindowNo, link));
                else
                    query.AddRestriction(link, Query.EQUAL, _ctx.GetContext(_curWindowNo, link));
            }
            //AZoomAcross zoom = new AZoomAcross(aZoomAcross.GetDropDownButton(), _curTab.GetTableName(), query, _curTab.GetAD_Window_ID());
            AZoomAcross zoom = new AZoomAcross(aZoomAcross, _curTab.GetTableName(), query, _curTab.GetAD_Window_ID(), this);
            //zoom.ShowPopup(bnavZoomAcross, _curTab.GetTableName(), query, windowV0.AD_Window_ID);

            zoom = null;
        }

        /// <summary>
        /// Request
        /// </summary>
        private void Cmd_Request()
        {
            int record_ID = _curTab.GetRecord_ID();
            log.Info("ID=" + record_ID);
            if (record_ID <= 0)
            {
                SetBusy(false);
                return;

            }

            int AD_Table_ID = _curTab.GetAD_Table_ID();
            int C_BPartner_ID = 0;
            object BPartner_ID = _curTab.GetValue("C_BPartner_ID");
            if (BPartner_ID != null)
                C_BPartner_ID = Convert.ToInt32(BPartner_ID);
            new ARequest(aRequest, AD_Table_ID, record_ID, C_BPartner_ID, this);
        }
        private void Cmd_Help()
        {
            Help help = new Help(_mWorkbench.GetMWindow(GetWindowIndex()));

            Utility.Envs.RegisterWindowForm(help);
            help.Show();
        }
        /// <summary>
        ///Open/View Archive
        /// </summary>
        private void Cmd_Archive()
        {
            int record_ID = _curTab.GetRecord_ID();
            log.Info("ID=" + record_ID);
            if (record_ID <= 0)
                return;

            int AD_Table_ID = _curTab.GetAD_Table_ID();
            new AArchive(null, AD_Table_ID, record_ID).OpenArchiveForm();
            // new ArchivedDocs(AD_Table_ID, record_ID).ShowDialog();
        }

        #endregion

        #region "Events"

        /// <summary>
        /// Handler of button Click Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        /* Buttom Process Variable */
        IControl btn = null;
        bool batch = false;
        bool startWOasking = false;
        Action actionProcessAfterSave = null;
        int recordId = -1;


        /// <summary>
        /// Button Click Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btn_click(object sender, RoutedEventArgs e)
        {
            IControl btn1 = null;
            try
            {
                btn = sender as IControl;
                btn1 = sender as IControl;
                btn1.SetDisabled(true);
                //MessageBox.Show(btn.GetAD_Process_ID().ToString() + "-----" + btn.GetValue());
                String columnName = btn.GetName();

                //  Zoom Button
                if (columnName.Equals("Record_ID"))
                {
                    int AD_Table_ID = _ctx.GetContextAsInt(_curWindowNo, "AD_Table_ID");
                    int Record_ID = _ctx.GetContextAsInt(_curWindowNo, "Record_ID");
                    AEnv.Zoom(AD_Table_ID, Record_ID);
                    return;
                }
                //save item
                if (NeedSave(false))
                {

                    if (!SaveData(true))
                        return;
                    else //Wait forAfterSave function and set action
                    {
                        actionProcessAfterSave = btnClickAfterSave; //Reaquire two parameter 

                    }

                    //return;//Make sure record is saved before running process
                }
                else
                {
                    btnClickAfterSave();
                }

            }
            catch (Exception ex)
            {
                if (btn != null)
                {
                    btn.SetDisabled(false);// .IsEnabled = true;
                }
                btn = null;
                batch = false;
                startWOasking = false;
                actionProcessAfterSave = null;
                //MessageBox.Show(" error in process : " + ex.Message + " and Source : " + ex.InnerException);

            }
            finally
            {
                if (btn1 != null)
                {
                    btn1.SetDisabled(false);
                    btn1 = null;

                }
            }
        }

        private void btnClickAfterSave()
        {
            string columnName = btn.GetName();
            startWOasking = false;
            batch = false;

            try
            {

                int tableId = _curTab.GetAD_Table_ID();
                recordId = _curTab.GetRecord_ID();// GetRecordID();
                //	Record_ID - Language Handling
                if (recordId == -1 && _curTab.GetKeyColumnName().Equals("AD_Language"))
                {
                    recordId = _ctx.GetContextAsInt(_curWindowNo, "AD_Language_ID");
                }
                //	Record_ID - Change Log ID
                if (recordId == -1 && (((IButton)btn).GetAD_Process_ID() == 306 || ((IButton)btn).GetAD_Process_ID() == 307))
                {
                    //Integer id = (Integer)m_curTab.getValue("AD_ChangeLog_ID");
                    int id = 0;//= int.Parse(_curTab.GetField("AD_ChangeLog_ID"));
                    recordId = id;
                }
                //	Record_ID - EntityType
                if (recordId == -1 && _curTab.GetKeyColumnName().Equals("EntityType"))
                {
                    //Integer id = (Integer)m_curTab.getValue("AD_EntityType_ID");
                    int id = 0;// = int.Parse(_curTab.GetField("AD_EntityType_ID"));
                    recordId = id;
                }
                //	Ensure it's saved
                if (recordId == -1 && _curTab.GetKeyColumnName().EndsWith("_ID"))
                {
                    //ADialog.error(m_curWindowNo, this, "SaveErrorRowNotFound");
                    ShowMessage.Error("SaveErrorRowNotFound", null, "");
                    return;
                }
                //	Pop up Payment Rules
                if (columnName.Equals("PaymentRule"))
                {
                    SetBusy(true, false);
                    VPayment vp = new VPayment(_curWindowNo, _curTab, btn as IButton);
                    vp.Closed += (s, evt) =>
                        {
                            if (vp.IsInitOK())
                            {
                                _curGC.DynamicDisplay(btn.GetName());
                                if (vp.btnTextChange)
                                {
                                    SetRowState(true, false);
                                    SetButtons(true, true);
                                }
                                if (vp.NeedSave())
                                {
                                    //cmd_save(false);
                                    //cmd_refresh();
                                    // bnavSaveItem_Click();
                                    //bnavRefresh_Click();
                                }
                                CheckAndCallProcess();
                            }
                        };
                    SetBusy(false, false);
                    return;
                }

                // Pop up Document Action (Workflow)
                else if (columnName.Equals("DocAction"))
                {
                    VDocAction vda = new VDocAction(_curWindowNo, _curTab, btn as IButton, recordId);
                    vda.Closed += (s, evt) =>
                        {
                            if (vda.GetNumberOfOptions() == 0)
                            {
                                vda = null;
                                log.Info("DocAction - No Options");
                                return;
                            }


                            _curGC.DynamicDisplay(btn.GetName());
                            if (!vda.IsStartProcess())
                                return;
                            batch = vda.IsBatch();
                            startWOasking = true;
                            vda = null;

                            CheckAndCallProcess();
                        };
                    // vda.Show();
                    return;

                }
                //  Pop up Create From
                else if (columnName.Equals("CreateFrom"))
                {

                    SetBusy(true, false);
                    //  m_curWindowNo
                    VCreateFrom vcf = VCreateFrom.Create(_curTab);
                    if (vcf != null)
                    {
                        vcf.Show();
                        vcf.Closing += new EventHandler<CancelEventArgs>(vcf_Closing);
                    }
                    SetBusy(false, false);
                    return;

                }
                //  Posting -----
                else if (columnName.Equals("Posted") && MRole.GetDefault().IsShowAcct())
                {

                    //  Check Doc Status
                    String processed = _ctx.GetContext(_curWindowNo, "Processed");
                    if (!processed.Equals("Y"))
                    {
                        String docStatus = _ctx.GetContext(_curWindowNo, "DocStatus");
                        if (DocActionVariables.STATUS_COMPLETED.Equals(docStatus)
                            || DocActionVariables.STATUS_CLOSED.Equals(docStatus)
                            || DocActionVariables.STATUS_REVERSED.Equals(docStatus)
                            || DocActionVariables.STATUS_VOIDED.Equals(docStatus))
                        {
                            ;
                        }
                        else
                        {
                            //ADialog.error(m_curWindowNo, this, "PostDocNotComplete");
                            ShowMessage.Error("PostDocNotComplete", true);
                            return;
                        }
                    }

                    //  Check Post Status
                    Object ps = _curTab.GetValue("Posted");
                    if (ps != null && ps.Equals("Y"))
                    {
                        ////new window
                        ////new acct.AcctViewer(_ctx.GetContextAsInt(_curWindowNo, "AD_Client_ID"),_curTab.GetAD_Table_ID(), _curTab.GetRecord_ID());
                        AcctViewer post = new VAdvantage.Framework.AcctViewer(_ctx.GetContextAsInt(_curWindowNo, "AD_Client_ID"), _curTab.GetAD_Table_ID(), _curTab.GetRecord_ID());
                        Utility.Envs.RegisterWindowForm(post);
                        post.Show();
                    }
                    else
                    {
                        ////if (ADialog.ask(m_curWindowNo, this, "PostImmediate?"))
                        ShowMessage.AskMessage("PostImmediate?", true, "").Closed += (sm, em) =>
                        {
                            if (true.Equals(((Message)sm).DialogResult))
                            {
                                SetBusy(true, false);
                                Envs.SetBusyIndicator(true);
                                bool force = ps != null && !ps.Equals("N");		//	force when problems
                                String error = null;
                                //String error = AEnv.PostImmediate(Env.GetCtx(), _curWindowNo, _ctx.GetAD_Client_ID(),
                                //_curTab.GetAD_Table_ID(), _curTab.GetRecord_ID(), force);
                                /*********************************************************/
                                //ServerBean s;
                                // TcpChannel tcp = new TcpChannel();

                                // IChannel[] chans = ChannelServices.RegisteredChannels;
                                //if (chans.Count() <= 0)
                                // ChannelServices.RegisterChannel(tcp, false);
                                try
                                {
                                    Ctx ctx = Envs.GetCtx();
                                    Dictionary<string, string> dic = (Dictionary<String, string>)ctx.GetMap();
                                    //s = (ServerBean)Activator.GetObject(typeof(ServerBean), "tcp://localhost:2090/ViennaFramework");
                                    //s = (ServerBean)Activator.GetObject(typeof(ServerBean), "tcp://" + VConnection.Get().Apps_host + ":" + VConnection.Get().Apps_port + "/" + "ViennaFramework");
                                    string sttr = "";
                                    //error = s.TryConnection(out sttr); //s.PostImmediate(Env.GetCtx(), _ctx.GetAD_Client_ID(), _curTab.GetAD_Table_ID(), _curTab.GetRecord_ID(), force, null);

                                    var client = AEnv.GetDSPWFClient();

                                    client.PostImmediateCompleted += (s, e) =>
                                    {
                                        if (e.Result != null && e.Result.Length > 0)
                                        {
                                            ShowMessage.Error(e.Result, true);
                                        }
                                        DataRowRefresh(true, null);
                                    };
                                    client.PostImmediateAsync(dic, _ctx.GetAD_Client_ID(), _curTab.GetAD_Table_ID(), _curTab.GetRecord_ID(), force, null);
                                    client.CloseAsync();
                                    //error = s.PostImmediate(dic, _ctx.GetAD_Client_ID(), _curTab.GetAD_Table_ID(), _curTab.GetRecord_ID(), force, null);
                                }
                                catch (Exception ex)
                                {
                                    ShowMessage.Error(ex.ToString(), true);
                                }
                                // _curTab.DataRefresh();
                                //if (error != null)
                                //{
                                //    //ADialog.error(m_curWindowNo, this, "PostingError-N", error);
                                //    ShowMessage.Error(error, true);
                                //}
                                Envs.SetBusyIndicator(false);
                            }
                        };
                    }
                    return;
                }   //  Posted
                //	Send Email -----
                else if (columnName.Equals("SendNewEMail"))
                {
                    //int AD_Process_ID = btn.GetAD_Process_ID();
                    //if (AD_Process_ID != 0)
                    //{
                    //}
                    ////	Mail Defaults
                    //String title2 = GetTitle();
                    //String to2 = null;
                    //Object oo = _curTab.GetValue("AD_User_ID");
                    //if (oo is int)
                    //{
                    //    MUser user = new MUser(VAdvantage.Utility.Envs.GetContext(), Util.GetValueOfInt(oo), null);
                    //    to2 = user.GetEMail();
                    //}
                    //if (to2 == null)
                    //{
                    //    to2 = (String)_curTab.GetValue("EMail");
                    //}
                    //String subject = (String)_curTab.GetValue("Name");
                    //;
                    //String message = "";
                    //VAdvantage.Framework.EMailDialog email = new EMailDialog(MUser.Get(VAdvantage.Utility.Envs.GetContext()), title2, to2, subject, message);
                    //email.Show();
                    //return;
                }

                else if (((IButton)btn).GetAD_Process_ID() == 0)
                {
                    IControl control = (IControl)btn;
                    String sql = "Select AD_Form_ID, ProcedureName from AD_CrystalReport_Bind Where AD_Window_ID = " + _curTab.GetAD_Window_ID() + " And ReportParameter = '" + control.GetName() + "' And AD_Table_ID = " + _curTab.GetAD_Table_ID();
                    SetBusy(true);
                    CrystalParameter para = new CrystalParameter(_curTab.GetWindowNo());
                    ThreadPool.QueueUserWorkItem(delegate
                    {
                        IDataReader dr = null;
                        int AD_Form_ID = 0;
                        String procName = "";


                        try
                        {
                            dr = DB.ExecuteReader(sql);
                            if (dr.Read())
                            {
                                AD_Form_ID = int.Parse(dr["AD_Form_ID"].ToString());
                                procName = dr["ProcedureName"].ToString();
                            }
                            dr.Close();
                            dr = null;
                        }
                        catch
                        {
                        }

                        if (AD_Form_ID == 0)
                        {
                            Dispatcher.BeginInvoke(delegate
                            {
                                SetBusy(false);
                             //   ShowMessage.Error("NoReportFormFoundError", false, "PleaseBindReport");
                                //this.Cursor = Cursors.Default;
                            });
                            return;
                        }

                        MForm form = new MForm(Envs.GetCtx(), AD_Form_ID, null);

                        if (form.IsReport())
                        {
                            MCrystalInstance instance = null;

                            try
                            {
                                instance = new MCrystalInstance(Envs.GetContext(), AD_Form_ID, 0);
                            }
                            catch (Exception ex)
                            {
                                Dispatcher.BeginInvoke(delegate
                                {
                                    SetBusy(false);
                                    // ShowMessage.Error("NoReportFormFoundError", false, "PleaseBindReport");
                                    //this.Cursor = Cursors.Default;
                                });
                                return;
                            }
                            if (!instance.Save())
                            {
                                Dispatcher.BeginInvoke(delegate
                                {
                                    SetBusy(false);
                                    ShowMessage.Error("NoReportFormFoundError", false, "PleaseBindReport");
                                    //this.Cursor = Cursors.Default;
                                });
                                return;
                            }

                            ProcessInfoParameter[] parameters = null;

                            para.SetAD_CrystalInstance_ID(instance.GetAD_CrystalInstance_ID());
                            List<String> colName = null;
                            List<object> colvalues = null;
                            if (para.InitDialog(AD_Form_ID, true, out colName))
                            {
                                if (procName.Trim().Length > 0)
                                {
                                    bool b = SetDBProcValues(colName, out colvalues);
                                    if (!b)
                                    {
                                        Dispatcher.BeginInvoke(delegate
                                        {
                                            SetBusy(false);
                                            ShowMessage.Error("CouldNotExecuteProcedure", false, procName);

                                        });
                                        //this.Cursor = Cursors.Default;
                                        //    
                                    }
                                    return;
                                }
                                //create parameter
                                for (int i = 0; i <= colName.Count - 1; i++)
                                {
                                    MCrystalInstancePara mpara = new MCrystalInstancePara(Envs.GetCtx(), instance.GetAD_CrystalInstance_ID(), i);
                                    mpara.SetParameterName(colName[i]);
                                    Object objResult = _curTab.GetValue(colName[i]);
                                    //date
                                    if (objResult == null)
                                    {
                                        Dispatcher.BeginInvoke(delegate
                                        {
                                            SetBusy(false);
                                            ShowMessage.Error("ValueNotFound", false, colName[i]);
                                            //this.Cursor = Cursors.Default;
                                        });
                                        //this.Cursor = Cursors.Default;
                                        return;
                                    }
                                    if (objResult is DateTime)
                                    {
                                        mpara.SetP_Date((DateTime?)objResult);
                                    }
                                    else if (objResult.GetType() == typeof(int))
                                    {
                                        if (objResult != null)
                                        {
                                            int ii = (int)objResult;
                                            mpara.SetP_Number(ii);
                                        }
                                    }
                                    else if (objResult.GetType() == typeof(decimal))
                                    {
                                        mpara.SetP_Number((decimal)objResult);
                                    }
                                    else if (objResult.GetType() == typeof(bool))
                                    {
                                        bool bln = (bool)objResult;
                                        String value = bln ? "Y" : "N";
                                        mpara.SetP_String(value);

                                    }
                                    else
                                    {
                                        if (objResult != null)
                                            mpara.SetP_String(objResult.ToString());
                                    }

                                    mpara.SetInfo(objResult.ToString());
                                    mpara.Save();
                                }
                                Dispatcher.BeginInvoke(delegate
                                {

                                    FormFrame ff = new FormFrame();
                                    // SwingUtilities.invokeLater(m_updatePB);			//	1
                                    ff.Set_Ad_CrystalInstance_ID(instance.GetAD_CrystalInstance_ID());
                                    ff.ColNames = colName;
                                    ff.ColValues = colvalues;
                                    ff.SetProcedureName(procName);
                                    ff.OpenForm(AD_Form_ID);
                                    SetBusy(false);
                                }
                                );
                                //this.Cursor = Cursors.Default;
                                //if (!ff.IsDisposed)
                                //  ff.ShowDialog();
                            }
                            else
                            {
                                Dispatcher.BeginInvoke(delegate
                                {
                                    FormFrame ff = new FormFrame();
                                    // SwingUtilities.invokeLater(m_updatePB);			//	1
                                    ff.Set_Ad_CrystalInstance_ID(instance.GetAD_CrystalInstance_ID());
                                    ff.OpenForm(AD_Form_ID);
                                    ff.ColNames = colName;
                                    ff.ColValues = colvalues;
                                    ff.SetProcedureName(procName);
                                    SetBusy(false);
                                });
                                //this.Cursor = Cursors.Default;
                                //if (!ff.IsDisposed)
                                //ff.ShowDialog();
                            }
                        }
                        else
                        {
                            Dispatcher.BeginInvoke(delegate
                            {
                                ShowMessage.Info("NoReportAttached", false, "", "");
                                SetBusy(false);
                            });
                            //this.Cursor = Cursors.Default;
                        }
                    });
                    //SetBusy(false);
                    return;
                }

                /**
                *  Start Process ----
                */

                CheckAndCallProcess();

            }
            catch (Exception ex)
            {
                btn = null;
                batch = false;
                startWOasking = false;
                actionProcessAfterSave = null;
                ShowMessage.Error(" error in process : " + ex.Message, null, " and Source : " + ex.InnerException);
            }

        }



        //void dService_ImportContactsCompleted(object sender, ImportContactsCompletedEventArgs e)
        //{
        //    if (e.Result != null)
        //    {
        //        if (e.ErrorMsg == null)
        //        {
        //            ObservableCollection<ContactsInfo> cInfo = e.Result;
        //            UserContactsContainer contact = new UserContactsContainer(cInfo, CanUpdateExiastingRecord);
        //            Envs.ShowForm(contact);
        //        }
        //        else
        //        {
        //            ShowMessage.Error(e.ErrorMsg, true);
        //            return;
        //        }
        //    }
        //    else
        //    {
        //        ;
        //    }
        //}







        void vcf_Closing(object sender, CancelEventArgs e)
        {

            CheckAndCallProcess();
            DataRowRefresh(true, null);
        }

        private void CheckAndCallProcess()
        {
            //log.Config("Process_ID=" + ((IButton)btn).GetAD_Process_ID() + ", Record_ID=" + record_ID);
            if (((IButton)btn).GetAD_Process_ID() == 0)
                return;
            //	Save item changed
            if (NeedSave(false))
            {
                if (!SaveData(true))
                    return;
                else//Wait for AfterSave event to fire
                {
                    actionProcessAfterSave = btnClickAfterSave2;
                }
            }
            else
            {
                btnClickAfterSave2();
            }
        }

        private void btnClickAfterSave2()
        {
            String columnName = btn.GetName();
            try
            {
                //	Ask user to start process, if Description and Help is not empty
                if (!startWOasking && !(((IButton)btn).GetDescription().Equals("") && ((IButton)btn).GetHelp().Equals("")))
                {
                    //if (!ShowMessage.Ask("StartProcess?", true, "\n" + btn.GetDescription() + "\n" + btn.GetHelp()))
                    //{
                    //    return;
                    //}
                }

                String title = ((IButton)btn).GetDescription();
                if (title == null || title.Length == 0)
                    title = columnName;
                ProcessInfo pi = new ProcessInfo(title, ((IButton)btn).GetAD_Process_ID(), _curTab.GetAD_Table_ID(), recordId);
                pi.SetAD_User_ID(_ctx.GetAD_User_ID());
                pi.SetAD_Client_ID(_ctx.GetAD_Client_ID());
                pi.SetIsBatch(batch);
                //start process
                ThreadPool.QueueUserWorkItem(delegate
                {
                    ProcessCtl ctl = new ProcessCtl(this, pi, null);
                    ctl.Process(_curWindowNo);
                });

            }
            catch (Exception ex)
            {
                ShowMessage.Error(" error in process : " + ex.Message, null, " and Source : " + ex.InnerException);
            }

            btn = null;
            batch = false;
            startWOasking = false;
            actionProcessAfterSave = null;
        }


        StringBuilder orclParams = null;

        private bool SetDBProcValues(List<string> list, out List<object> colvalues)
        {
            colvalues = new List<object>();
            try
            {

                for (int i = 0; i < list.Count; i++)
                {
                    colvalues.Add(_curTab.GetValue(list[i]));
                }
                return true;
            }
            catch
            {
                return false;
            }
        }


        #endregion

        #region "AsyncProcess"
        //use for store value weather UI is locked or not
        private volatile bool _isLocked = false;

        //use for track weahter tab data refreshed after call doc action or not
        private volatile bool _isRfreshed = false;
        void ASyncProcess.ExecuteASync(ProcessInfo pi)
        {
            log.Config("-");
        }

        bool ASyncProcess.IsUILocked()
        {
            return _isLocked;
        }

        void ASyncProcess.LockUI(ProcessInfo pi)
        {
            //	//log.fine("" + pi);
            _isLocked = true;
            Dispatcher.BeginInvoke(delegate
            {
                SetBusy(true, false);
                Utility.Envs.SetBusyIndicator(true);
            });


        }   //  lockUI

        void ASyncProcess.UnlockUI(ProcessInfo pi)
        {
            _isLocked = false;
            //	//log.fine("" + pi);
            bool notPrint = pi != null
                && pi.GetAD_Process_ID() != _curTab.GetAD_Process_ID();
            //  Process Result
            if (notPrint)		//	refresh if not print 
            {
                //enable fire event
                blockEvent = false;

                //	Timeout
                if (pi.IsTimeout())		//	set temporarily to R/O
                    Envs.GetContext().SetContext("Processed", "Y");

                //	Update Status Line

                //	Get Log Info
                ProcessInfoUtil.SetLogFromDB(pi);
                String logInfo = pi.GetLogInfo(false);



                Dispatcher.BeginInvoke(delegate
                {
                    SetStatusLine(pi.GetSummary(), pi.IsError());
                    if (logInfo.Length > 0)
                    {
                        //implemented by jagmohan Bhatt on 24-aug-2009
                        //if (this.InvokeRequired)
                        //{
                        //    Invoke(new ShowDialogDelegate(ShowMessage.Info), new object[] { pi.GetTitle(), true, logInfo, "" });
                        //}
                        ////Message form = new Message(pi.GetTitle(), logInfo, Message.MessageType.INFORMATION);
                        ////form.ShowDialog();
                        ////MessageBox.Show(logInfo);
                        ShowMessage.Info(pi.GetTitle(), true, logInfo, "");	//	 clear text
                    }
                });
            }

        }


        /// <summary>
        /// Refresh UI 
        /// </summary>
        void ASyncRefreshUI.RefreshUI(ProcessInfo pi)
        {
            bool notPrint = pi != null
                && pi.GetAD_Process_ID() != _curTab.GetAD_Process_ID();
            //
            //SetBusy(true);

            //  Process Result
            if (notPrint)		//	refresh if not print 
            {
                //Refresh the current tab if varible is true, set this varibel value form the 
                // process thread if process is not related to print.
                //disable fire event
                blockEvent = true;
                //refresh selected row
                DataRowRefresh(true, pi);

                //refresh UI for grid mode
                //_curGC.ReDrawCurrentRow();

                //reset dyanamic display and refresh UI for single mode
                //_curGC.DynamicDisplay("");

                //enable fire event
                //blockEvent = false;
                //System.Threading.Thread.Sleep(100);
                //SetStatusLine(pi.GetSummary(), pi.IsError());
            }
            Dispatcher.BeginInvoke(delegate
            {
                Utility.Envs.SetBusyIndicator(false);
                SetBusy(false, true);
            });
        }



        // Delete to make message form modal
        public delegate void ShowDialogDelegate(string title, bool? bl, string message, string className);
        #endregion

        #region "OtherFunctions"

        public void SetSaveButton(bool enable)
        {
            aSave.SetEnabled(enable);
        }

        public bool IsSaveEnabled()
        {
            return aSave.IsEnabled();
        }

        private void BusyGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;

        }

        private void BusyGrid_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        public void SetWindowName(string name)
        {
            txtWindow.Text = name;
        }

        internal void SetWindowImage(System.Windows.Media.Imaging.BitmapImage img)
        {
            if (img != null)
                imgWindow.Source = img;
        }

        internal System.Windows.Media.Imaging.BitmapImage GetImage()
        {
            return _mWorkbench.GetImage(GetWindowIndex());
        }


        /// <summary>
        ///	Get Current Tab
        /// </summary>
        /// <returns></returns>
        public GridTab GetCurrentTab()
        {
            return _curTab;
        }	//	getCurrentTab
        public GridController GetCurrentGC()
        {
            return _curGC;
        }	//	ge


        #endregion

        #region IBusy
        public void SetBusy(bool isbusy)
        {
            SetBusy(isbusy, false);
        }
        #endregion
    }

    /// <summary>
    /// Helper Class For MuntiSave Record(Product Window)
    /// </summary>
    internal class MultiSaveHelper
    {
        /* Current Grid Controller */
        private GridController curGC;
        /* Current Tab */
        private GridTab curTab;
        /*flag */
        private bool isCompleted = false;
        /* Complet event */
        internal event EventHandler Completed;
        /* Key Values */
        private List<object> newValues;
        /* Key Column */
        private string colName;
        /* Flag First Call */
        private bool firstTime = true;
        /* Grid Field */
        GridField lineField = null;
        //Trx */
        Trx trx = null;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="_curGC"></param>
        /// <param name="_curTab"></param>
        /// <param name="_newValues"></param>
        /// <param name="_colName"></param>
        public MultiSaveHelper(GridController _curGC, GridTab _curTab, object[] _newValues, string _colName)
        {
            // TODO: Complete member initialization
            curGC = _curGC;
            curTab = _curTab;
            newValues = _newValues.ToList(); ;
            colName = _colName;
        }

        /// <summary>
        /// Start Processing
        /// </summary>
        internal void Start()
        {
            //_curTab.GetTableObj().isMultipleProduct = true;

            curGC.InsertCompleted += new EventHandler(InsertCompletedFirstTime);

            curGC.SaveData(false, true);
            lineField = curTab.GetField("Line");

        }

        /// <summary>
        /// First Call 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void InsertCompletedFirstTime(object sender, EventArgs e)
        {
            var evt = e as VAdvantage.Panels.GridController.MultiSaveEventArgs;
            curGC.InsertCompleted -= new EventHandler(InsertCompletedFirstTime);

            if (!evt.IsSaved)
            {
                //curTab.GetTableObj().isMultipleProduct = true;
                isCompleted = false;
                FireCompleted();
                return;
            }

            CheckNewList();
        }

        /// <summary>
        /// Check For key Values
        /// </summary>
        /// <returns></returns>
        private bool CheckNewList()
        {
            if (newValues.Count < 1)
            {
                isCompleted = true;
                FireCompleted();
                return false;
            }



            curGC.OnNewRowInserted += new EventHandler(curGC_OnNewRowInserted);
            curGC.AddNewRow(true);

            //    throw new Exception("Could not clone tab");


            //curTab.SetValue(colName, values[i]);

            //if (lineField != null)
            //{
            //    _curTab.SetValue(lineField, 0);
            //}

            //if (!_curGC.SaveData(false))
            //{
            //    throw new Exception("Could not update tab");
            //}

            return true;
        }

        /// <summary>
        /// On  New Row Inserted
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void curGC_OnNewRowInserted(object sender, EventArgs e)
        {
            curGC.OnNewRowInserted -= new EventHandler(curGC_OnNewRowInserted);
            if (((NewEventArgs)e).IsNew)
            {
                object value = newValues[0];
                newValues.RemoveAt(0);

                ThreadPool.QueueUserWorkItem(delegate
                {
                    curTab.SetValue(colName, value);

                    if (lineField != null)
                    {
                        curTab.SetValue(lineField, 0);
                    }

                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {
                        curGC.InsertCompleted += new EventHandler(curGC_InsertCompleted);
                        if (!curGC.SaveData(false, true))
                        {
                            isCompleted = false;
                            FireCompleted();
                            return;
                            //throw new Exception("Could not update tab");
                        }
                    });
                });
            }
            else
            {
                isCompleted = false;
                FireCompleted();
                return;

            }// throw new Exception("Could not clone tab");
        }

        /// <summary>
        /// Row Insert Completed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void curGC_InsertCompleted(object sender, EventArgs e)
        {
            curGC.InsertCompleted -= new EventHandler(curGC_InsertCompleted);
            VAdvantage.Panels.GridController.MultiSaveEventArgs evt = e as VAdvantage.Panels.GridController.MultiSaveEventArgs;

            if (evt.IsSaved)
            {
                CheckNewList();
            }
            else
            {
                isCompleted = false;
                FireCompleted();
                return;
            }
        }

        /// <summary>
        /// invoke Completed event
        /// </summary>
        internal void FireCompleted()
        {
            Dispose();
            if (Completed != null)
            {
                Completed(this, new CompletedEventArgs(isCompleted));
            }
        }

        /// <summary>
        /// Dispose
        /// </summary>
        private void Dispose()
        {
            curGC = null;
            curTab = null;
            newValues = null;
        }
    }

    /// <summary>
    /// Completed Event Args(used in MuliSave Helper)
    /// </summary>
    internal class CompletedEventArgs : EventArgs
    {
        internal bool Completed
        {
            get;
            set;
        }
        internal CompletedEventArgs(bool isCompleted)
        {
            Completed = isCompleted;
        }
    }
}
